Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useEffect } from "react";
- import Box from "@mui/material/Box";
- import Grid from "@mui/material/Grid";
- import Stack from "@mui/material/Stack";
- import Typography from "@mui/material/Typography";
- import IconButton from "@mui/material/IconButton";
- import ArrowBackOutlinedIcon from "@mui/icons-material/ArrowBackOutlined";
- import {
- AddAddressDrawer,
- ChooseLocationCard,
- ChooseServiceCard,
- CustomButton,
- DescriptionCard,
- ErrorHandler,
- SavedAddressDrawer,
- StyledToggleButtonGroup,
- SubscriptionOverviewCard,
- } from "../../components";
- import { RightArrowStripesIcon } from "../../assets";
- import { withDrawer, withSnackBar } from "../../HOC's";
- import { ACTIVITY_MODE_TYPE, drawerProps, snackProps } from "../../utils";
- import ChooseSlot from "./chooseSlot";
- import { useLocation, useParams } from "react-router";
- import { useDispatch, useSelector } from "react-redux";
- import { actions } from "tanyacare-middleware";
- import { CustomCard } from "../../components/composedComponents/subscriptions/customCard";
- import { useHistory } from "react-router-dom";
- import { routes } from "../../router/routes";
- import { useDateValidation } from "@mui/lab/internal/pickers/hooks/useValidation";
- const MAX_LETTER_COUNT = 200;
- const {
- GET_CLIENT_SUBSCRIPTION_DETAILS,
- GET_CLIENT_ADDRESS,
- GET_ADDRESS_TYPES,
- // UPDATE_SUBSCRIPTION_REFUND_STATUS,
- // DELETE_ACTIVITY,
- } = actions;
- function ServiceBooking(props) {
- const dispatch = useDispatch();
- const location = useLocation();
- const history = useHistory();
- const params = useParams();
- const { drawer, snack } = props;
- const isEdit = location?.state?.isEdit ?? false;
- // Store States
- const subscriptionData = useSelector(
- (state) => state?.clientSubscription?.getSubscriptionDetails
- );
- const clientAddress = useSelector(
- (state) => state?.clientAddress?.getAddress
- );
- const address_type = useSelector(
- (state) => state?.clientMaster?.clientAddressTypes
- );
- const validateArray = (testData) => {
- return Array.isArray(testData) && testData?.length > 0 ? testData : [];
- };
- //
- const { loading, error, data } = subscriptionData;
- // unique services list with
- const getServices = () => {
- const filtereServiceOptions = data?.services?.map((service) => ({
- ...service,
- label: `${service?.name}${
- service?.pending_services_count > 0 ? " (1)" : ""
- }`,
- value: service?.id,
- }));
- if (!isEdit) {
- filtereServiceOptions?.filter(
- (option) => option?.pending_services_count > 0
- );
- }
- const key = "id";
- const serviceOptions = [
- ...new Map(
- filtereServiceOptions?.map((item) => [item[key], item])
- ).values(),
- ];
- return serviceOptions;
- };
- const filterServiceAndServiceId = (id) => {
- if (id) {
- const serviceData = getServices()?.filter(
- (service) => service?.id === id
- )?.[0];
- return {
- serviceId: location.state?.serviceId,
- selectedService: serviceData,
- };
- }
- return {};
- };
- // Component States
- const [, setNotFound] = useState(false);
- // getServices()?.[0]?.value
- const [serviceId, setServiceId] = useState(null);
- // getServices()?.[0]
- const [selectedService, setSelectedService] = useState(null);
- const [mode, setMode] = useState({});
- const [address, setAddress] = useState({});
- const [selectedVenue, setSelectedVenue] = useState("");
- const [description, setDescription] = useState("");
- const [client_address, setClientAddress] = useState([])
- const [clientAddressLoader, setClientAddressLoader] = useState(true)
- useEffect(() => {
- // if()
- dispatch(GET_CLIENT_ADDRESS({}))
- // .then((res) => {
- // debugger
- // // setClientAddress(res?.payload?.data)
- // // setClientAddressLoader(false)
- // })
- // .catch((err) => console.error(err));
- }, [dispatch]);
- useEffect(() => {
- if (params?.id) {
- dispatch(GET_ADDRESS_TYPES({}));
- getSubscriptionDetailsData(params?.id);
- } else {
- setNotFound(true);
- }
- }, []);
- // Setting the initial state if user navigated to book a service from detail page services row.
- useEffect(() => {
- // debugger;
- const id = location?.state?.serviceId;
- const { serviceId: filteredServiceId, selectedService: filteredService } =
- filterServiceAndServiceId(id);
- setServiceId(filteredServiceId);
- setSelectedService(filteredService);
- let act_mode = filteredService?.modeOfActivity;
- if (act_mode?.length < 2) {
- setMode(act_mode?.[0]);
- }
- }, [location]);
- // const getEditedService = () => {
- // const filtereServiceOptions = location?.state?.edit_data?.service?.map((service) => ({
- // ...service,
- // label: `${service?.name}${
- // service?.pending_services_count > 0 ? " (1)" : ""
- // }`,
- // value: service?.id,
- // })).filter(
- // (option) => option?.pending_services_count > 0
- // );
- // const key = "id";
- // const serviceOptions = [
- // ...new Map(
- // filtereServiceOptions?.map((item) => [item[key], item])
- // ).values(),
- // ];
- // return location?.state?.edit_data?.service;
- // }
- const filterEditedServiceAndServiceId = (id) => {
- if (id) {
- const serviceData = location?.state?.edit_data?.service;
- return {
- serviceId: location.state?.serviceId,
- selectedService: serviceData,
- };
- }
- return {};
- };
- useEffect(() => {
- // debugger;
- const isEdit = location?.state?.isEdit;
- const id = location?.state?.serviceId;
- const { serviceId: filteredServiceId, selectedService: filteredService } =
- filterEditedServiceAndServiceId(id);
- setServiceId(filteredServiceId);
- setSelectedService(filteredService);
- let activity_mode_options = [];
- if (Array.isArray(location?.state?.edit_data?.service?.modeOfActivity)) {
- activity_mode_options = [
- ...location?.state?.edit_data?.service?.modeOfActivity,
- ];
- }
- let selected_mode = activity_mode_options?.filter(
- (mode) => mode?.value === location?.state?.edit_data?.mode
- )?.[0];
- setMode(selected_mode);
- setDescription(location?.state?.description)
- // Promise.resolve(dispatch(GET_CLIENT_ADDRESS({})))
- // .then((res) => {
- // // setClientAddress(res?.payload?.data)
- // debugger
- onSavedAddressSelect(location?.state?.edit_data?.selectedVenue)
- // })
- // .catch((err) => console.error(err));
- // let act_mode = filteredService?.modeOfActivity;
- // if (act_mode?.length < 2) {
- // setMode(act_mode?.[0]);
- // }
- }, [location?.state?.isEdit]);
- const getSubscriptionDetailsData = (id) => {
- Promise.resolve(dispatch(GET_CLIENT_SUBSCRIPTION_DETAILS({ id: id })))
- .then((res) => {
- // if (isEdit) {
- // debugger;
- // let event = {
- // target: {
- // value: location.state?.edit_data?.service?.id,
- // },
- // };
- // handleServiceChange(event, location.state?.edit_data?.mode);
- // }
- })
- .catch((err) => console.error(err));
- };
- const navigateToTracking = () => {
- // Navigate to tracker
- if (history) history.push(routes.tracker.pathName);
- };
- const continueBooking = () => {
- if (!selectedService?.id) {
- return snack.setSnack({
- open: true,
- message: "Please choose the service to continue",
- severity: snackProps.severity.error,
- });
- }
- if (!mode?.value) {
- return snack.setSnack({
- open: true,
- message: "Please choose the mode of activity",
- severity: snackProps.severity.error,
- });
- }
- if (mode?.value === ACTIVITY_MODE_TYPE?.IN_PERSON && !address) {
- return snack.setSnack({
- open: true,
- message: "Please choose the address to continue",
- severity: snackProps.severity.error,
- });
- }
- const selectedData = {
- activity_type_id: selectedService?.id,
- // title: isEdit
- // ? params?.data?.title
- // : `Appointment for ${selectedService?.name ?? 'Service'}`,
- title: `Appointment for ${selectedService?.name ?? "Service"}`,
- activityTypeName: selectedService?.name,
- serviceId: selectedService?.id,
- subscriptionId: subscriptionData?.data?.id,
- subscriptionType: subscriptionData?.data?.subscriptionType,
- duration: selectedService?.duration,
- providerId: selectedService?.partnerId,
- resourceTypeCategoryId: selectedService?.resourceTypeCategoryId,
- // ...params?.data,
- address:
- mode?.value === ACTIVITY_MODE_TYPE.VIDEO
- ? null
- : address?.add_location?.address,
- selectedVenue: selectedVenue,
- description: description,
- latitude:
- mode?.value === ACTIVITY_MODE_TYPE.VIDEO
- ? null
- : `${address?.add_location?.latitude}` ?? null,
- longitude:
- mode?.value === ACTIVITY_MODE_TYPE.VIDEO
- ? null
- : `${address?.add_location?.longitude}` ?? null,
- mode: mode?.value,
- };
- // If everything okay continue booking
- drawer.setDrawer({
- open: true,
- anchor: drawerProps.direction.right,
- component: (handleClose) => (
- <ChooseSlot
- data={selectedData}
- navigateToTracking={navigateToTracking}
- handleClose={handleClose}
- />
- ),
- sx: {
- Drawer: {
- "& .MuiDrawer-paper": {
- minHeight: "100vh",
- maxWidth: "600px",
- },
- },
- },
- });
- };
- const handleServiceChange = (event, userSelectedMode) => {
- setServiceId(event.target.value);
- let act_mode = getServices()?.filter(
- (service) => service?.id === event.target.value
- )?.[0]?.modeOfActivity;
- setSelectedService(
- getServices()?.filter(
- (service) => service?.id === event.target.value
- )?.[0]
- );
- if (userSelectedMode) {
- return setMode(userSelectedMode);
- } else if (act_mode?.length < 2) {
- setMode(act_mode?.[0]);
- }
- };
- useEffect(() => {
- console.log("_______________________________");
- console.log(selectedService);
- });
- const handleModeChange = (event, newMode) => {
- const selectedMode = selectedService?.modeOfActivity?.filter(
- (activityMode) => activityMode?.value === newMode
- )?.[0];
- if (newMode !== null) {
- setMode(selectedMode);
- }
- };
- const handleDescriptionChange = (evt) => {
- if (evt.target.value?.length <= MAX_LETTER_COUNT) {
- setDescription(evt.target.value);
- }
- };
- // Selected Saved Address
- const onSavedAddressSelect = (addressId) => {
- debugger
- if (addressId) {
- const { data: selectedAddress = [] } = clientAddress ?? {} ;
- console.clear()
- console.log(selectedAddress)
- if(Array.isArray(selectedAddress))
- {
- const addressObj = selectedAddress?.filter(
- (addressItem) => addressItem?.value === addressId
- )?.[0];
- setAddress(addressObj);
- setSelectedVenue(addressObj?.value);
- }
- }
- props.drawer.setDrawer({
- open: false,
- });
- };
- const onSavedAddressButtonClick = () => {
- const { data: selectedAddress } = clientAddress ?? {};
- props.drawer.setDrawer({
- open: true,
- component: (handleClose) => (
- <SavedAddressDrawer
- data={
- Array.isArray(selectedAddress) && selectedAddress?.length > 0
- ? selectedAddress
- : []
- }
- value={address}
- onSave={onSavedAddressSelect}
- handleClose={handleClose}
- />
- ),
- });
- };
- const onNewAddressSave = (newLocation) => {
- // Close the drawer first
- props.drawer.setDrawer({
- open: false,
- });
- setAddress({ add_location: { ...newLocation } });
- setSelectedVenue("NEW_ADDRESS");
- };
- const onAddEditAddressButtonClick = () => {
- props.drawer.setDrawer({
- open: true,
- component: (handleClose) => (
- <AddAddressDrawer
- isEdit={selectedVenue === "NEW_ADDRESS"}
- data={address}
- options={validateArray(address_type?.data)}
- onSave={onNewAddressSave}
- handleClose={handleClose}
- />
- ),
- });
- };
- if (error) {
- return (
- <Stack sx={{ height: "100%", width: "100%" }}>
- <ErrorHandler onRetry={() => getSubscriptionDetailsData(params?.id)} />
- </Stack>
- );
- }
- return (
- <Box sx={{ p: 2 }}>
- {/* <Typography
- variant="body1"
- color="textSecondary"
- sx={{ pt: { xs: 1, sm: 1 } }}
- >
- Breadcrumbs section
- </Typography> */}
- <Typography variant="h6" sx={{ pt: { xs: 1, sm: 1 }, fontWeight: 500 }}>
- <IconButton size="small" onClick={() => history.goBack()}>
- <ArrowBackOutlinedIcon fontSize="small" />
- </IconButton>
- Subscription Booking
- </Typography>
- {/* Main Container */}
- <Box sx={{ py: 2 }}>
- <Grid container spacing={2}>
- <Grid item xs={12}>
- <SubscriptionOverviewCard
- loading={loading}
- data={data}
- showCallToActions={false}
- />
- </Grid>
- <Grid container item xs={12} md={6} spacing={2}>
- <Grid item xs={12} md={12}>
- <ChooseServiceCard
- loading={loading}
- options={getServices()}
- value={serviceId}
- onChange={handleServiceChange}
- isEdit={isEdit ? true : false}
- />
- </Grid>
- <Grid item xs={12} md={12}>
- <DescriptionCard
- value={description}
- onChange={handleDescriptionChange}
- maxCount={MAX_LETTER_COUNT}
- />
- </Grid>
- </Grid>
- <Grid container item xs={12} md={6} spacing={2}>
- {Array?.isArray(selectedService?.modeOfActivity) &&
- selectedService?.modeOfActivity?.length > 0 && (
- <Grid item xs={12} md={12}>
- <CustomCard title={"Mode of Activity"}>
- {/* Modes */}
- <Box sx={{ py: 2, px: 3.5 }}>
- <StyledToggleButtonGroup
- data={mode}
- options={selectedService?.modeOfActivity}
- onChange={handleModeChange}
- />
- </Box>
- </CustomCard>
- </Grid>
- )}
- {mode?.value === ACTIVITY_MODE_TYPE.IN_PERSON && (
- <Grid item xs={12} md={12}>
- <ChooseLocationCard
- data={address}
- label={"address"}
- isEdit={selectedVenue === "NEW_ADDRESS"}
- onSavedAddressButtonClick={onSavedAddressButtonClick}
- onAddEditAddressButtonClick={onAddEditAddressButtonClick}
- />
- </Grid>
- )}
- </Grid>
- <Grid item xs={12} md={12}>
- <Stack
- sx={{
- flexDirection: "row",
- gap: 2,
- height: "100%",
- justifyContent: "flex-end",
- alignItems: "flex-end",
- flexWrap: { xs: "wrap-reverse", md: "nowrap" },
- }}
- >
- {/* <Box sx={{ minWidth: 100 }}>
- <CustomButton
- fullWidth
- variant="outlined"
- color="primary"
- sx={{
- bgcolor: "background.paper",
- border: 0,
- color: "text.primary",
- minHeight: (theme) => theme.spacing(5),
- "&:hover": {
- bgcolor: "background.paper",
- border: 0,
- },
- }}
- >
- Cancel
- </CustomButton>
- </Box> */}
- <Box>
- <CustomButton
- onClick={continueBooking}
- fullWidth
- endIcon={<RightArrowStripesIcon />}
- >
- Continue Booking
- </CustomButton>
- </Box>
- </Stack>
- </Grid>
- </Grid>
- </Box>
- </Box>
- );
- }
- export default withSnackBar(withDrawer(ServiceBooking));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement