Untitled

 avatar
unknown
plain_text
9 months ago
13 kB
1
Indexable
import React, { useEffect, useState } from 'react';
import { Col, Collapse, Form, Row } from 'react-bootstrap';
import { Controller, useFormContext, useWatch } from 'react-hook-form';
import { CalProfitMargin, DpProtection } from '../../../../utils/CommonUtils';
import Select from 'react-select';
import { DateField } from '@mainComponent/common/FormFields';

const customStyles = {
  menu: provided => ({ ...provided, zIndex: 10 }),
  placeholder: provided => ({ ...provided, color: '#ced4da', fontStyle: 'Italic' }),
  singleValue: provided => ({...provided, color: '#007bff'})
}

const Detail = ({ isEditForm, stores, units, productTaxTypes, prePath, defaultValues, maxPriceDp }) => {
  const defaultPrePath = prePath || 'catalog_product_new_form'
  const { errors, control, register, setError } = useFormContext();
  const watchedFields = useWatch({
    control,
    name: [`${defaultPrePath}[detail][cost_price]`, `${defaultPrePath}[detail][base_price]`, `${defaultPrePath}[product_class][type]`, `${defaultPrePath}[detail][track_inventory]`],
    defaultValue: defaultValues
  });
  const costPrice = +watchedFields[`${defaultPrePath}[detail][cost_price]`]
  const basePrice = +watchedFields[`${defaultPrePath}[detail][base_price]`]
  const isComposite = watchedFields[`${defaultPrePath}[product_class][type]`] === 'is_composite'
  const isPackage = watchedFields[`${defaultPrePath}[product_class][type]`] === 'is_package'
  const isSetmenu = watchedFields[`${defaultPrePath}[product_class][type]`] === 'is_set_menu'
  const trackInventory = watchedFields[`${defaultPrePath}[detail][track_inventory]`]
  const [profit, setProfit] = useState(0)

  useEffect(() => {
    setProfit(CalProfitMargin(basePrice, isComposite ? 0 : costPrice))
  }, [isComposite, costPrice, basePrice])

  return (
    <Row>
      <Form.Group as={Col} md={8}>
        <Form.Label className="required-tag">
          Product Name
        </Form.Label>
        <Form.Control
          type='text'
          name={`${defaultPrePath}[detail][name]`}
          ref={register({
            required: 'This field is required'
          })}
        />
        {errors?.[defaultPrePath]?.["detail"]?.["name"] && (
          <Form.Control.Feedback className="d-block" type="invalid">
          {typeof errors[defaultPrePath]["detail"]["name"].message === "object" ?
            errors[defaultPrePath]["detail"]["name"].message.map((mes, i) => (
              <span className="d-block" key={"name"+i}>{mes}</span>
            )) : errors[defaultPrePath]["detail"]["name"].message}
          </Form.Control.Feedback>
        )}
      </Form.Group>
      <Form.Group as={Col} md={4}>
        <Form.Label className="required-tag">
          SKU
        </Form.Label>
        <Form.Control
          type='text'
          name={`${defaultPrePath}[detail][sku]`}
          ref={register({
            required: 'This field is required'
          })}
        />
        {errors?.[defaultPrePath]?.["detail"]?.["sku"] && (
          <Form.Control.Feedback className="d-block" type="invalid">
            {typeof errors[defaultPrePath]["detail"]["sku"].message === "object" ?
              errors[defaultPrePath]["detail"]["sku"].message.map((mes, i) => (
                <span className="d-block" key={"sku"+i}>{mes}</span>
            )) : errors[defaultPrePath]["detail"]["sku"].message}
          </Form.Control.Feedback>
        )}
      </Form.Group>
      <Col md={8}>
        <Row>
          {!isComposite ? (
            <Form.Group as={Col} xs={6} md={4}>
              <Form.Label>
                Cost Price
              </Form.Label>
              <Controller
                control={control}
                name={`${defaultPrePath}[detail][cost_price]`}
                render={({onChange, value, name, ref}) => {
                  return (
                    <Form.Control
                      type='number'
                      name={name}
                      value={value}
                      onChange={onChange}
                      onBlur={(e) => {
                        return onChange(DpProtection(e.currentTarget.value, maxPriceDp))
                      }}
                      ref={ref}
                      step="any"
                    />
                  )
                }}
              />
              {errors?.[defaultPrePath]?.["detail"]?.["cost_price"] && (
                <Form.Control.Feedback className="d-block" type="invalid">
                {typeof errors[defaultPrePath]["detail"]["cost_price"].message === "object" ?
                  errors[defaultPrePath]["detail"]["cost_price"].message.map((mes, i) => (
                    <span className="d-block" key={"cost_price"+i}>{mes}</span>
                  )) : errors[defaultPrePath]["detail"]["cost_price"].message}
                </Form.Control.Feedback>
              )}
            </Form.Group>
          ) : null}
          <Form.Group as={Col} xs={6} md={4}>
            <Form.Label className="required-tag">
              Base Price
            </Form.Label>
            <Controller
              control={control}
              name={`${defaultPrePath}[detail][base_price]`}
              rules={{
                required: 'This field is required'
              }}
              render={({onChange, value, name, ref}) => {
                return (
                  <Form.Control
                    type='number'
                    name={name}
                    value={value}
                    onChange={(e) => {
                      if (isSetmenu) {
                        return setError(name, {
                          type: 'manual',
                          message:
                            'Cannot change default base price for Set menu product. You can edit Set menu price by editing its separators prices.',
                        })
                      }

                      onChange(e)
                    }}
                    onBlur={(e) => {
                      return onChange(
                        DpProtection(e.currentTarget.value, maxPriceDp)
                      )
                    }}
                    ref={ref}
                    step='any'
                  />
                )
              }}
            />
            {errors?.[defaultPrePath]?.["detail"]?.["base_price"] && (
              <Form.Control.Feedback className="d-block" type="invalid">
              {typeof errors[defaultPrePath]["detail"]["base_price"].message === "object" ?
                errors[defaultPrePath]["detail"]["base_price"].message.map((mes, i) => (
                  <span className="d-block" key={"base_price"+i}>{mes}</span>
                )) : errors[defaultPrePath]["detail"]["base_price"].message}
              </Form.Control.Feedback>
            )}
          </Form.Group>
          <Form.Group as={Col} md={4}>
            <Form.Label>
              Profit Margin
            </Form.Label>
            <div>{profit.toFixed(2)} %</div>
          </Form.Group>
          <Form.Group as={Col} md={12}>
            <Form.Check
              type='checkbox'
              id='[detail][open_price]'
            >
              <Form.Check.Input
                type='checkbox'
                name={`${defaultPrePath}[detail][open_price]`}
                ref={register}
              />
              <Form.Check.Label className="input-color">Allow open price for product</Form.Check.Label>
            </Form.Check>
            {errors?.[defaultPrePath]?.["detail"]?.["open_price"] && (
              <Form.Control.Feedback className="d-block" type="invalid">
              {typeof errors[defaultPrePath]["detail"]["open_price"].message === "object" ?
                errors[defaultPrePath]["detail"]["open_price"].message.map((mes, i) => (
                  <span className="d-block" key={"open_price"+i}>{mes}</span>
                )) : errors[defaultPrePath]["detail"]["open_price"].message}
              </Form.Control.Feedback>
            )}
          </Form.Group>
        </Row>
      </Col>
      <Form.Group as={Col} md={4}>
        <Form.Label>
          Tax Types
        </Form.Label>
        <Controller
          as={Select}
          options={productTaxTypes}
          name={`${defaultPrePath}[detail][product_tax_type]`}
          styles={customStyles}
          isSearchable
          placeholder='Select a product tax type...'
          getOptionLabel={option => option.name}
          getOptionValue={option => option.id}
          control={control}
        />
        {errors?.[defaultPrePath]?.["detail"]?.["product_tax_type"] && (
          <Form.Control.Feedback className="d-block" type="invalid">
          {typeof errors[defaultPrePath]["detail"]["product_tax_type"].message === "object" ?
            errors[defaultPrePath]["detail"]["product_tax_type"].message.map((mes, i) => (
              <span className="d-block" key={"product_tax_type"+i}>{mes}</span>
            )) : errors[defaultPrePath]["detail"]["product_tax_type"].message}
          </Form.Control.Feedback>
        )}
      </Form.Group>
      <Collapse in={!isSetmenu}>
        <Form.Group as={Col} md={8}>
          <Form.Check
            type='checkbox'
            id='[detail][track_inventory]'
          >
            <Form.Check.Input
              type='checkbox'
              name={`${defaultPrePath}[detail][track_inventory]`}
              ref={register}
            />
            <Form.Check.Label className="input-color">Track Inventory for this product</Form.Check.Label>
          </Form.Check>
          {errors?.[defaultPrePath]?.["detail"]?.["track_inventory"] && (
            <Form.Control.Feedback className="d-block" type="invalid">
            {typeof errors[defaultPrePath]["detail"]["track_inventory"].message === "object" ?
              errors[defaultPrePath]["detail"]["track_inventory"].message.map((mes, i) => (
                <span className="d-block" key={"track_inventory"+i}>{mes}</span>
              )) : errors[defaultPrePath]["detail"]["track_inventory"].message}
            </Form.Control.Feedback>
          )}
        </Form.Group>
      </Collapse>
      {isEditForm ? (
        <Collapse in={trackInventory}>
          <Form.Group as={Col} md={8}>
            <Form.Label className="required-tag">
              Unit of measure
            </Form.Label>
            <Controller
              as={Select}
              options={units}
              name={`${defaultPrePath}[detail][unit_of_measure]`}
              styles={customStyles}
              isSearchable
              control={control}
            />
            {errors?.[defaultPrePath]?.["detail"]?.["unit_of_measure"] && (
              <Form.Control.Feedback className="d-block" type="invalid">
              {typeof errors[defaultPrePath]["detail"]["unit_of_measure"].message === "object" ?
                errors[defaultPrePath]["detail"]["unit_of_measure"].message.map((mes, i) => (
                  <span className="d-block" key={"unit_of_measure"+i}>{mes}</span>
                )) : errors[defaultPrePath]["detail"]["unit_of_measure"].message}
              </Form.Control.Feedback>
            )}
          </Form.Group>
        </Collapse>
      ) : (
        <Collapse in={trackInventory && !isComposite && !isPackage}>
          <Form.Group as={Col} md={8}>
            <Form.Label className="required-tag">
              Initial QTY
            </Form.Label>
            <Row>
              <Col md={6}>
                <Controller
                  as={Select}
                  options={stores}
                  name={`${defaultPrePath}[detail][store]`}
                  styles={customStyles}
                  isSearchable
                  placeholder='Select an outlet...'
                  getOptionLabel={option => option.name}
                  getOptionValue={option => option.external_source_id}
                  control={control}
                />
              </Col>
              <Col md={3}>
                <Controller
                  control={control}
                  name={`${defaultPrePath}[detail][quantity]`}
                  render={({onChange, value, name, ref}) => {
                    return (
                      <Form.Control
                        type='number'
                        name={name}
                        value={value}
                        onChange={(e) => {
                          if (+e.target.value >= 0) {
                            onChange(e)
                          }
                        }}
                        ref={ref}
                      />
                    )
                  }}
                />
              </Col>
            </Row>
          </Form.Group>
        </Collapse>

      )}
      <DateField
        inputGroupProps={{
          className: 'custom-datefield'
        }}
        showMonthDropdown
        placeholderText="Expiry date"
        dateFormat="dd/MM/yyyy"
        labelClasses="control-label"
        label="End date"
        name={`${defaultPrePath}[detail][expiry_date]`}
        control={control}
        error={errors.expiry_date}
        withoutAppend
        rules={{
          required: 'This field is required'
        }}
      />
    </Row>
  );
}

export default Detail;
Editor is loading...
Leave a Comment