documentContainer Update

This commit is contained in:
=bhagwanSingh 2025-08-27 16:50:22 +05:30
parent 645bf0cb8d
commit 25d878b53d
33 changed files with 620 additions and 1272 deletions

4
.env
View File

@ -1,3 +1,3 @@
# VITE_BASE_URI="https://officially-powerful-goat.ngrok-free.app"
VITE_BASE_URI="https://officially-powerful-goat.ngrok-free.app"
# VITE_BASE_URI="https://python-amused-adder.ngrok-free.app"
VITE_BASE_URI="https://concrete-gladly-mullet.ngrok-free.app"
# VITE_BASE_URI="https://concrete-gladly-mullet.ngrok-free.app"

View File

@ -14,7 +14,7 @@ const DocumentPages = ({ selectedDocuments, setDropDownTogglePage, dropDownToggl
const [currentPage, setCurrentPage] = useState(0);
return (
<div className='bg-white h-full p-4 overflow-y-auto'>
<div className='p-4'>
<div className="flex flex-col gap-2">
{selectedDocuments && selectedDocuments.length && selectedDocuments.map((document, indx) => {
@ -34,7 +34,7 @@ const DocumentPages = ({ selectedDocuments, setDropDownTogglePage, dropDownToggl
document.pages != undefined && <img
key={indx}
className='rounded-sm shadow'
src={document.pages[0].src}
src={"data:image/png;base64," + document.thumbnail}
alt="" />
}

View File

@ -1,9 +1,9 @@
import { useEffect, useLayoutEffect, useState } from "react";
import { useEffect, useState } from "react";
import axios from "axios"
import { RootState } from "../../store/store";
import { useNavigate, useParams } from "react-router-dom"
import { DroppedItem, DroppedItemsObj, TagsTypes } from "../../utlity/types";
import { DroppedItem, TagsTypes } from "../../utlity/types";
import Loader from "../dashboard/Loader";
import SignCon from "../signature/SignCon";
@ -11,24 +11,22 @@ import { Bounce, toast } from "react-toastify";
import { useDispatch, useSelector } from "react-redux";
import { hideLoader, showLoader } from "../../store/slices/loaderSlice";
import { FaRegImage, FaFileAlt, FaSignature, FaStamp, FaCheck, FaQuestionCircle } from 'react-icons/fa'
import { FaFileAlt, FaSignature, FaStamp, FaCheck, FaQuestionCircle } from 'react-icons/fa'
import { IoIosDocument, IoMdClose } from 'react-icons/io'
import { MdKeyboardArrowDown } from 'react-icons/md'
import { TbChevronsDownLeft, TbSignature } from "react-icons/tb";
import { TbSignature } from "react-icons/tb";
import { BsFileArrowDownFill } from "react-icons/bs";
import dayjs from "dayjs";
import maskUtils from "../../utlity/maskUtils";
import StampUpload from "../stamp/StampUpload";
import TermsModal from "./TermsModal";
import DocumentPages from "./DocumentPages";
import FieldList from "../process/processStepTwo/FieldList";
import typeToIconMap from "../../helper/iconMap";
import { droppedTagsDefaultField } from "../process/processStepTwo/DocumentContainer";
import SignCompletionScreen from "./SignCompletionScreen";
import api from "../../config/api";
import RightSideBar from "../process/processStepTwo/rightSideBar/RightSideBar";
import { RiDragMoveFill } from "react-icons/ri";
import { handleGroupBorderPosition } from "../../utlity/tagGroupConUtils";
import RightSideBar from "../process/processStepTwo/rightSideBar/RightSideBar";
@ -45,6 +43,7 @@ interface RecipientType {
phone: string | null;
index: number;
type: string;
provideOwnTags: boolean;
recipientStatus: string;
authType: string | null;
language: string | null;
@ -134,6 +133,11 @@ const fitObj = [
},
]
enum RightSideNav {
ATTRIBUTES = "attributes",
PAGES = "pages"
}
// Functions - LIST
// handleSignClick - Handle when sign || Initial tag got clicked
// fetchData - Fetch document pages and tags data
@ -157,6 +161,7 @@ const SignDocument = () => {
const [stamp, setStamp] = useState<StampTypeObj>({ open: false, blob: "" });
const [rightSideNavToggle, setRightSideNavToggle] = useState<RightSideNav>(RightSideNav.PAGES);
// Handling Date Opacity
const [dateValues, setDateValues] = useState<{ [key: string]: string }>({});
@ -348,6 +353,8 @@ const SignDocument = () => {
setTransaction(res?.data?.transaction)
setRecSignStatus(res?.data?.status)
if (res?.data?.details.provideOwnTags) setRightSideNavToggle(RightSideNav.ATTRIBUTES)
if ("provideOwnTags" in res?.data?.details && res?.data?.details.provideOwnTags) {
setProvideTags(true)
}
@ -938,6 +945,10 @@ const SignDocument = () => {
};
const handleSetIsFields = (setTo: boolean) => {
if (setTo !== isFields) setIsFields(setTo);
}
// const [showTerms, setShowTerms] = useState<boolean>(true);
return (
@ -990,6 +1001,19 @@ const SignDocument = () => {
</div>
{/* FIT - END */}
{provideTags && <div
onClick={() => handleSetIsFields(true)}
className={`flex items-center gap-1 cursor-pointer text-xs px-2 py-1 rounded-sm ${isFields ? 'bg-slate-100' : ''}`}>
<IoIosDocument />
<p className='tracking-wide'>Fields</p>
</div>}
<div
onClick={() => handleSetIsFields(provideTags ? false : !isFields)}
className={`flex items-center gap-1 cursor-pointer text-xs px-2 py-1 rounded-sm ${!isFields ? 'bg-slate-100' : ''}`}>
<IoIosDocument />
<p className='tracking-wide'>Pages</p>
</div>
</div>
@ -1060,17 +1084,21 @@ const SignDocument = () => {
{/* <div className="lg:col-span-2 bg-slate-100 h-full p-4 overflow-y-auto"></div> */}
<div
id="tags-list-client-side"
className={`col-span-2 h-full p-4 overflow-y-auto ${provideTags ? "bg-white" : "order-last"}`}>
{recipientId && provideTags && <FieldList color={"#8f87f1"} recipientId={Number(recipientId)} recipientIndx={0} acntId={"1"} />}
className={`col-span-2 h-full ${isFields ? "p-4" : ""} overflow-y-auto bg-white ${!provideTags && isFields ? "hidden" : ""}`}>
{isFields && recipientId && provideTags && <FieldList color={"#8f87f1"} recipientId={Number(recipientId)} recipientIndx={0} acntId={"1"} />}
{!isFields && <DocumentPages
selectedDocuments={selectedDocuments}
setDropDownTogglePage={setDropDownTogglePage}
dropDownTogglePage={dropDownTogglePage} />}
</div>
{/* Pages - END */}
{/* Main container */}
<div
id="doc-con"
className="zoom-con relative col-span-8 px-4 bg-slate-100 h-full w-full overflow-auto scroll-smooth"
className={`zoom-con relative ${!isFields || (isFields && provideTags) ? "col-span-10" : "col-span-12"} px-4 bg-slate-100 h-full w-full overflow-auto scroll-smooth transition-all duration-200`}
>
{
@ -1669,15 +1697,9 @@ const SignDocument = () => {
</div>
<div className={`col-span-2 ${provideTags ? "" : "order-first"} overflow-y-auto`}>
{selectedDocuments !== null && <DocumentPages
selectedDocuments={selectedDocuments}
setDropDownTogglePage={setDropDownTogglePage}
dropDownTogglePage={dropDownTogglePage} />}
{/* {provideTags && selectedTag && selectedTag !== null && "key" in selectedTag && "index" in selectedTag &&
{provideTags && selectedTag && selectedTag !== null && "key" in selectedTag && "index" in selectedTag &&
<div className={`col-span-2 ${provideTags ? "" : "order-first"} h-full ${!isFields ? "bg-white" : isFields && provideTags ? "bg-white" : ""} overflow-y-auto`}>
{/* Right Side Attributes Section if providedTags - START */}
<RightSideBar
droppedItems={droppedItems}
selectedTag={droppedItems[selectedTag.index]}
@ -1685,11 +1707,10 @@ const SignDocument = () => {
selTagKey={selectedTag.key}
selTagIndx={selectedTag.index}
signClient={true}
/>} */}
/>
{/* Right Side Attributes Section if providedTags - END */}
</div>
}
{/* Right Side - START */}
{/* <div className="col-span-2 bg-slate-100 h-full p-4 overflow-y-auto">

View File

@ -24,7 +24,10 @@ const StartNow = () => {
const transactionId = transactionRes.data.id
const formData = new FormData();
formData.append("file", filesToUpload[0]);
filesToUpload.forEach(file => {
formData.append("file", file);
});
dispatch(uploadDocuments({ formData, accountId, transactionId }))
.unwrap()

View File

@ -125,13 +125,13 @@ const StartSection = () => {
</div>
{/* Recent Data Section */}
<div className="grid grid-cols-1 md:grid-cols-1 lg:grid-cols-2 gap-2 mt-5">
<div className="grid grid-cols-1 md:grid-cols-1 lg:grid-cols-1 gap-2 mt-5">
<section className="w-full">
<TransactionDataTable activeAccountId={activeAccountId}/>
</section>
<section className="w-full">
{/* <section className="w-full">
<TemplateTable />
</section>
</section> */}
</div>
</section>

View File

@ -1,69 +0,0 @@
import { useState } from "react";
import { FaPlus } from "react-icons/fa";
type RecipientAddCardProps = {
addRecipient: (name: string, email: string, type: "mailToSign" | "inPerson" | "cc") => void; // Adjust the parameter type as needed
};
const RecipientAddCard: React.FC<RecipientAddCardProps> = ({ addRecipient }) => {
const [recipient] = useState()
const handleRecipientAdd = () => {
}
return (
<div className="p-4 bg-[var(--primaryLight)] shadow-sm mb-4 w-[650px] rounded-md">
<p className="pb-4 text-md">Add Recipient Details</p>
<div className="py-1">
<input
type="text"
placeholder="Recipient Name"
className="w-full p-2 rounded mb-2 bg-white"
/>
</div>
<div className="py-1">
<input
type="email"
placeholder="Recipient Email"
className="w-full p-2 rounded mb-2 bg-white"
/>
</div>
<div className="flex justify-between py-2">
<div className="flex gap-4 justify-end">
{[
{ label: "Mail To Sign", value: "mailToSign" },
{ label: "In-Person", value: "inPerson" },
{ label: "CC", value: "cc" }
].map((option) => (
<label key={option.value} className="flex items-center gap-2">
<input
type="radio"
name={`send-type`}
value={option.value}
defaultChecked={option.value === "mailToSign"}
className="accent-blue-500"
/>
{option.label}
</label>
))}
</div>
<button
// onClick={addRecipient}
className="flex cursor-pointer items-center gap-2 bg-green-500 text-white px-4 py-2 rounded-lg shadow-md hover:bg-green-600"
>
<FaPlus /> Add Recipient
</button>
</div>
</div>
);
};
export default RecipientAddCard;

View File

@ -39,7 +39,7 @@ const DocumentCard: React.FC<DocumentCardProps> = ({ id, name, isCompleted , tra
let lastUpdate = 0;
const delay = 1000;
const docProgSSE = new EventSource(`http://192.168.2.112:8083/api/progress/${id}`);
const docProgSSE = new EventSource(`http://192.168.2.176:8083/api/progress/${id}`);
docProgSSE.addEventListener('progress', (event) => {
const jsonData = JSON.parse(event.data);

View File

@ -47,16 +47,6 @@ const ProcessStepOne = () => {
const [editCase, setEditCase] = useState<string>("")
const [editRecipient, setEditRecipient] = useState({})
// if (!accountId || !transactionId) {
// window.location.href = "/";
// return null;
// }
// const selectedDocuments = useSelector((state: RootState) => state.selectedDocuments.selectedDocuments)
// const { selectedDocuments, signType } = useSelector((state: RootState) => state.selectedDocuments)
const selectedDocuments = useSelector((state: RootState) => state.documents.documents)
const selectedRecipients = useSelector((state: RootState) => state.selectedRecipients.recipients)
const [showSelfSignWarnModal, setShowSelfSignWarnModal] = useState(false)
@ -82,13 +72,9 @@ const ProcessStepOne = () => {
}, 5000); // hide icon while typing, show it again after 500ms of no input
};
// const userData = useSelector((state: RootState) => state.user)
const [transactionDetails, setTransactionDetails] = useState<any>([]);
useEffect(() => {
// <<<<<<< HEAD
// Fetching Transaction Details - START
(async () => {
try {
const res = await api.get(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`);
@ -105,31 +91,24 @@ const ProcessStepOne = () => {
} catch (e) {
}
})()
// Fetching Transaction Details - END
// =======
// (async () => {
// const res = await api.get(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`)
// })()
// >>>>>>> origin/main
// (async () => {
// const res = await api.get(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`)
// })()
selectedRecipients.length === 0 && dispatch(fetchRecipients({ accountId, transactionId }));
selectedDocuments.length === 0 && dispatch(fetchDocuments({ accountId, transactionId }));
}, [])
// const signingOrder = useSelector((state: RootState) => state.selectedRecipients.signingOrder)
// const user = useSelector((state: RootState) => state.user)
const [emailDtls, setEmailDtls] = useState<EmailDtls>({ subject: "Documents for Signature", message: "" });
useEffect(() => {
dispatch(hideLoader());
}, [])
const getMinRoutingOrder = () => {
return selectedRecipients.reduce((min, recipient) => {
return Math.min(min, recipient.routingOrder ?? Infinity);
}, Infinity);
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const handleNextClick = async (saveAndClose: boolean = false) => {
@ -208,13 +187,13 @@ const ProcessStepOne = () => {
dispatch(showLoader("Processing Recipients..."));
let minRoutingOrder = 1
selectedRecipients.forEach((recipient) => {
if (recipient.routingOrder ?? 1 < minRoutingOrder) {
minRoutingOrder = recipient.routingOrder ?? 1;
}
});
let minRoutingOrder = getMinRoutingOrder();
// selectedRecipients.forEach((recipient) => {
// if (recipient.routingOrder ?? 1 < minRoutingOrder) {
// minRoutingOrder = recipient.routingOrder ?? 1;
// }
// });
const recipientsData = selectedRecipients.map((recipient, index) => ({
id: "id" in recipient ? recipient.id : null,
routingOrder: "routingOrder" in recipient && recipient.routingOrder ? recipient.routingOrder : 1,
@ -248,11 +227,10 @@ const ProcessStepOne = () => {
await Promise.all(
selectedRecipients.map((recipient) => dispatch(removeRecipientAsync({
recipientId: recipient.id,
email: recipient.email,
accountId,
transactionId,
}))
)
email: recipient.email,
})))
);
recipientsDataTemp = [{
@ -273,9 +251,11 @@ const ProcessStepOne = () => {
phone: "",
accessCode: "",
accessCodeDelivery: true,
language: "en",
language: userData.language ? userData.language : "en",
name: `${userData.firstName} ${userData.lastName}`,
roleName: ""
roleName: "",
allowSenderToEdit: true,
allowSenderToDelete: true,
}]
try {
@ -287,7 +267,8 @@ const ProcessStepOne = () => {
}
} else {
await dispatch(addRecipientAsync({ recipientsData: recipientsDataTemp, accountId, transactionId }));
if(!accountId || !transactionId) return;
dispatch(addRecipientAsync({ recipientsData: recipientsDataTemp, accountId, transactionId }));
}
dispatch(showLoader("Processing Message..."));
@ -297,11 +278,6 @@ const ProcessStepOne = () => {
status: "CREATED"
})
// if (isSendNow) {
// dispatch(updateTransactionStatus(TRANSACTION_STATUS_ENUMS.TRANSACTION_SEND_SUCCESS));
// }
// else {
// setTimeout(() => {
dispatch(resetDocuments())
dispatch(resetRecipients())
if (transactionTemplateToggle === TRANSACTION_TEMPLATE_TOGGLE.TEMPLATES) {
@ -397,7 +373,7 @@ const ProcessStepOne = () => {
className='flex items-center gap-3'>
{transactionTemplateToggle === TRANSACTION_TEMPLATE_TOGGLE.TEMPLATES && <button
onClick={() => handleNextClick(false, true)}
onClick={() => handleNextClick(false)}
className="text-sm px-4 py-2 rounded bg-[var(--primary)] text-white shadow hover:bg-[var(--primaryLight2)] transition cursor-pointer"
>
Save & Close
@ -446,13 +422,13 @@ const ProcessStepOne = () => {
(signType !== SignTypeEnum.selfSign || showSelfSignWarnModal) &&
<div className="flex flex-col gap-4 align-start">
<RecipientCards transactionTemplateToggle={transactionTemplateToggle} setEditRecipient={setEditRecipient} setEditCase={setEditCase} editRecipient={editRecipient} setEditRecipientCurrentEmail={setEditRecipientCurrentEmail} editRecipientCurrentEmail={editRecipientCurrentEmail} />
<RecipientCards userEmail={userData.email} getMinRoutingOrder={getMinRoutingOrder} transactionTemplateToggle={transactionTemplateToggle} setEditRecipient={setEditRecipient} setEditCase={setEditCase} editRecipient={editRecipient} setEditRecipientCurrentEmail={setEditRecipientCurrentEmail} editRecipientCurrentEmail={editRecipientCurrentEmail} />
<div
ref={topRef}
className={`relative w-full bg-[var(--mainViewBg)] ${globalLoader.isLoading ? 'pointer-events-none' : ''}`}
>
<RecipientAddCard transactionTemplateToggle={transactionTemplateToggle} editRecipient={editRecipient} editCase={editCase} setEditRecipient={setEditRecipient} setEditCase={setEditCase} topRef={topRef} setEditRecipientCurrentEmail={setEditRecipientCurrentEmail} />
<RecipientAddCard userEmail={userData.email} getMinRoutingOrder={getMinRoutingOrder} transactionTemplateToggle={transactionTemplateToggle} editRecipient={editRecipient} editCase={editCase} setEditRecipient={setEditRecipient} setEditCase={setEditCase} topRef={topRef} setEditRecipientCurrentEmail={setEditRecipientCurrentEmail} />
</div>
</div>

View File

@ -26,20 +26,20 @@ export interface ContactTypeObj {
}
const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase, setEditRecipient, setEditCase, topRef, setEditRecipientCurrentEmail }) => {
const [activeAccountId, setActiveAccountId] = useState<string | null>(
const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase, setEditRecipient, setEditCase, topRef, setEditRecipientCurrentEmail, showCard = false, recipientData = null }) => {
const [activeAccountId, setActiveAccountId] = useState<string | null>(
JSON.parse(sessionStorage.getItem('activeAccountId') || 'null')
);
const recipients = useSelector((state: RootState) => state.selectedRecipients.recipients);
const [contactData, setContactData] = useState<ContactTypeObj>({ type: "", contacts: [] });
const [openContactModal, setOpenContactModal] = useState(false);
const dispatch = useDispatch<AppDispatch>();
const formRef = useRef<HTMLFormElement | null>(null);
const [recipient, setRecipients] = useState<Recipient>({ uuid: null, newOne: false, firstName: "", lastName: "", email: "", hostName: "", hostEmail: "", roleName: "", type: recipientType.SIGNER, allowSenderToEdit: true, allowSenderToDelete: true });
const [recipient, setRecipients] = useState<Recipient>(recipientData !== null ? {...recipientData} : { uuid: null, newOne: false, firstName: "", lastName: "", email: "", hostName: "", hostEmail: "", roleName: "", type: recipientType.SIGNER, allowSenderToEdit: true, allowSenderToDelete: true } );
const [showAdvanceSettings, setShowAdvanceSettings] = useState(false)
@ -216,9 +216,11 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
updatedRecipient.hostEmail = "";
}
if (editCase === "Edit") {
dispatch(updateRecipient(updatedRecipient));
} else {
updatedRecipient.routingOrder = 1;
dispatch(addRecipient({
...updatedRecipient,
uuid: uuidv4(),
@ -264,6 +266,7 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
const handleFocus = async (field: "firstName" | "lastName" | "email") => {
setManualFocusTriggered(true);
setOpenContactModal(true);
setActiveField(field);
@ -273,7 +276,7 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
try {
const res = await api.get(`/api/accounts/${activeAccountId}/contacts?pageSize=10`);
const contacts = res.data?.content || [];
setCachedContacts(contacts);
setCachedContacts([...contacts]);
setFilteredContacts(contacts);
setContactData({ type: field, contacts });
setHasFetchedInitial(true);
@ -292,9 +295,10 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
useDebouncedEffect(() => {
if (!activeField || !manualFocusTriggered) return;
const inputValue = recipient[activeField].trim().toLowerCase();
console.log(inputValue, "Line 297", activeField)
if (inputValue.length === 0) {
setFilteredContacts(cachedContacts);
setContactData({ type: activeField, contacts: cachedContacts });
@ -314,12 +318,21 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
return;
}
if (lastQuery !== inputValue) {
if(lastQuery !== null && inputValue.startsWith(lastQuery)) return
setLastQuery(inputValue);
api
.get(`/api/accounts/${activeAccountId}/contacts?pageSize=5&${activeField}=${inputValue}`)
.then((res) => {
console.log(res, "Printing RES")
const fetched = res.data?.content || [];
setCachedContacts([...fetched]);
setFilteredContacts(fetched);
setContactData({ type: activeField, contacts: fetched });
setOpenContactModal(true);
@ -480,7 +493,7 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
onBlur={handleContactModalBlur}
value={recipient.firstName}
placeholder="First Name"
className={` w-full px-4 py-2 border rounded-md text-sm focus:outline-none transition
className={`w-full px-4 py-2 border rounded-md text-sm focus:outline-none transition
${errors.firstName ? 'border-red-500 ring-2 ring-red-300' : 'border-gray-300 focus:ring-2 focus:ring-[var(--primary)]'}`}
onChange={(e) => {
setRecipients({ ...recipient, firstName: e.target.value });
@ -594,12 +607,12 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
))}
</div>
<button
{!showCard && <button
type="submit"
className="inline-flex items-center gap-2 bg-[var(--primary)] hover:bg-[var(--primaryLight2)] text-white text-sm font-semibold px-5 py-2 rounded-md transition"
>
<FaPlus size={14} /> {editCase === "Edit" ? "Edit Recipient" : "Add Recipient"}
</button>
</button>}
</div>
</form>
</div>

View File

@ -26,6 +26,8 @@ const getInitials = (name: string) => {
};
type CardsData = {
userEmail: string;
getMinRoutingOrder: () => number;
editRecipient: any;
setEditRecipient: (recipient: any) => void; // Replace `any` with the actual type if known
setEditCase: (string: any) => void;
@ -36,11 +38,10 @@ type CardsData = {
};
const RecipientCards = ({ setEditRecipient, setEditCase, transactionTemplateToggle, editRecipient, editCase, setEditRecipientCurrentEmail, editRecipientCurrentEmail }: CardsData) => {
const RecipientCards = ({ userEmail, getMinRoutingOrder, setEditRecipient, setEditCase, transactionTemplateToggle, editRecipient, editCase, setEditRecipientCurrentEmail, editRecipientCurrentEmail }: CardsData) => {
const templateId = useParams<{ templateId: string }>().templateId;
let { accountId, transactionId } = useParams<{ accountId: string, transactionId: string }>();
const dispatch = useDispatch();
if (!transactionId) {
@ -59,12 +60,15 @@ const RecipientCards = ({ setEditRecipient, setEditCase, transactionTemplateTogg
};
const handleEditRecipient = (recipient) => {
const provideOwnTags = userEmail === recipient.email && (recipient.routingOrder ?? 1) === getMinRoutingOrder() ? true : false;
// alert(JSON.stringify(recipient))
setEditCase('Edit')
setEditRecipient(recipient)
setEditRecipient({...recipient, provideOwnTags})
if (recipient.uuid) {
setEditRecipientCurrentEmail(recipient.uuid)
}else{
} else {
setEditRecipientCurrentEmail(recipient.id)
}
}
@ -148,11 +152,13 @@ const RecipientCards = ({ setEditRecipient, setEditCase, transactionTemplateTogg
{recipients.length > 1 ? <div className="relative">
<input
type="number"
value={recipient.routingOrder || 1}
min={1}
onChange={(e) =>
handleOrderChange(recipient.id || recipient.email, Number(e.target.value))
}
value={recipient.routingOrder ? recipient.routingOrder : ""}
// min={1}
onChange={(e) => {
let val = e.target.value.replace(/^0+(?=\d)/, "");
console.log(val, "Line 155")
handleOrderChange(recipient.id || recipient.email, Number(val))
}}
className="w-10 h-6 text-center rounded text-sm text-gray-600 focus:outline-none focus:ring-[var(--primary)] border border-dashed border-gray-400 bg-slate-100"
/>
{/* <RiPencilFill className="absolute top-1.5 right-0 text-[14px] text-gray-500" /> */}
@ -160,71 +166,71 @@ const RecipientCards = ({ setEditRecipient, setEditCase, transactionTemplateTogg
: <input
type="number"
disabled
value={recipient.routingOrder || 1}
value={recipient.routingOrder}
min={1}
onChange={(e) =>
handleOrderChange(recipient.id || recipient.email, Number(e.target.value))
}
className="w-8 text-center rounded text-sm text-gray-700 border-none focus:outline-none focus:ring-[var(--primary)]"
/>}
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-[var(--primary)] text-white flex items-center justify-center font-semibold text-xs select-none">
{getInitials(`${recipient.firstName} ${recipient.lastName || ""}`)}
</div>
<div className="min-w-0">
<p className="font-semibold text-gray-800 truncate text-sm">
{recipient.firstName} {recipient.lastName || ""}
</p>
<p className="text-xs text-gray-500 truncate">
{recipient.email} | {recipient.type} {recipient.roleName ? `| Role : ${recipient.roleName}` : ""}
</p>
</div>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-[var(--primary)] text-white flex items-center justify-center font-semibold text-xs select-none">
{getInitials(`${recipient.firstName} ${recipient.lastName || ""}`)}
</div>
{signType !== "self-sign" && (
<div className="flex justify-between gap-2 items-center">
{/* Edit Button */}
<button
type="button"
title="Edit recipient"
aria-label={`Edit recipient ${recipient.firstName}`}
onClick={() => handleEditRecipient(recipient)}
disabled={
// For templates: always enabled (never disabled)
['templates'].includes(transactionTemplateToggle)
? false
: // For transactions: disabled if not newOne AND not allowed to edit
(!recipient.newOne && !recipient.allowSenderToEdit)
}
className="text-gray-400 hover:text-blue-600 transition-colors cursor-pointer disabled:opacity-50"
>
<FiEdit size={16} />
</button>
{/* Delete Button */}
<button
type="button"
title="Remove recipient"
aria-label={`Remove recipient ${recipient.firstName}`}
onClick={() => handleRemoveRecipient(recipient)}
disabled={
// For templates: always enabled (never disabled)
['templates'].includes(transactionTemplateToggle)
? false
: // For transactions: disabled if not newOne AND not allowed to delete
(!recipient.newOne && !recipient.allowSenderToDelete)
}
className="text-gray-400 hover:text-red-600 transition-colors cursor-pointer disabled:opacity-50"
>
<ImBin size={16} />
</button>
</div>
)}
<div className="min-w-0">
<p className="font-semibold text-gray-800 truncate text-sm">
{recipient.firstName} {recipient.lastName || ""}
</p>
<p className="text-xs text-gray-500 truncate">
{recipient.email} | {recipient.type} {recipient.roleName ? `| Role : ${recipient.roleName}` : ""}
</p>
</div>
</div>
)
{signType !== "self-sign" && (
<div className="flex justify-between gap-2 items-center">
{/* Edit Button */}
<button
type="button"
title="Edit recipient"
aria-label={`Edit recipient ${recipient.firstName}`}
onClick={() => handleEditRecipient(recipient)}
disabled={
// For templates: always enabled (never disabled)
['templates'].includes(transactionTemplateToggle)
? false
: // For transactions: disabled if not newOne AND not allowed to edit
(!recipient.newOne && !recipient.allowSenderToEdit)
}
className="text-gray-400 hover:text-blue-600 transition-colors cursor-pointer disabled:opacity-50"
>
<FiEdit size={16} />
</button>
{/* Delete Button */}
<button
type="button"
title="Remove recipient"
aria-label={`Remove recipient ${recipient.firstName}`}
onClick={() => handleRemoveRecipient(recipient)}
disabled={
// For templates: always enabled (never disabled)
['templates'].includes(transactionTemplateToggle)
? false
: // For transactions: disabled if not newOne AND not allowed to delete
(!recipient.newOne && !recipient.allowSenderToDelete)
}
className="text-gray-400 hover:text-red-600 transition-colors cursor-pointer disabled:opacity-50"
>
<ImBin size={16} />
</button>
</div>
)}
</div>
)
)}
</div>
</>

View File

@ -52,8 +52,10 @@ const SelectedDocuments = ({transactionTemplateToggle}) => {
const handleUpload = (filesToUpload: File[]) => {
const formData = new FormData();
formData.append("file", filesToUpload[0])
console.log(formData, "Line 59")
filesToUpload.forEach(file => {
formData.append("file", file);
});
// filesToUpload.forEach((file) => formData.append("document", file));
dispatch(uploadDocuments({ formData, accountId, transactionId }))

View File

@ -2,7 +2,7 @@ import { useNavigate } from "react-router-dom";
type PropsType = {
setShowSelfSignWarnModal: (val: boolean) => void;
onConfirm: () => void;
onConfirm?: () => void;
};
const SelfSignWarnModal = ({ setShowSelfSignWarnModal }: PropsType) => {

View File

@ -21,6 +21,7 @@ import Loader from '../../dashboard/Loader';
import { handleGroupBorderPosition } from '../../../utlity/tagGroupConUtils';
import { hideLoader, showLoader } from '../../../store/slices/loaderSlice';
import { IsSendInterface } from './ProcessStepTwo';
import DroppedItemsTagsCon from './DroppedItemsTagsCon';
export interface DroppedItemsObj {
[key: string]: DroppedItem[]
@ -235,7 +236,7 @@ const DocumentContainer: React.FC<DocumentContainerProps> = ({ transactionSaving
return tagsData;
};
const sendTagsToRecipients = async (
const sendTagsToRecipients = async (
tagsData: Record<number, any[]>,
accountId: string,
transactionId: string
@ -390,31 +391,19 @@ const DocumentContainer: React.FC<DocumentContainerProps> = ({ transactionSaving
// }
// }
let updatedTags : any = [];
let updatedTags: any = [];
for (const dropPagesId of Object.keys(droppedItems)) {
console.log("Dropped Item:", droppedItems[dropPagesId]);
updatedTags.push(...droppedItems[dropPagesId]);
}
console.log(updatedTags, "updatedTags")
let tagsData = groupByRecipientId(updatedTags);
await sendTagsToRecipients(tagsData, accountId, transactionId);
// if (save) {
// if (selectedRecipients.length === 0) return;
// fetchTags();
// setSelectedTag(null)
// }
return
// SENDING Transaction - START
if (!save) {
const res = await api.put(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`, { status: "SENT" })
// const res = await api.put(`/api/accounts/${accountId}/transactions/${transactionId}`, { status: "SENT" })
console.log(res, "Check123")
dispatch(hideLoader())
}
// SENDING Transaction - END
@ -426,16 +415,16 @@ const DocumentContainer: React.FC<DocumentContainerProps> = ({ transactionSaving
}, [isSend])
// Save Tags - END
useEffect(() => {
// setTimeout(() => {
const interval = setInterval(async () => {
// debugger
setTransactionSaving(true)
// handleTransactionProcess(true);
}, 8000)
// }, 8000)
return () => clearInterval(interval);
}, [droppedItems])
// handleTransactionSaving - START
// useEffect(() => {
// const interval = setInterval(async () => {
// setTransactionSaving(true)
// }, 8000)
// return () => clearInterval(interval);
// }, [droppedItems])
// handleTransactionSaving - END
useEffect(() => {
if (transactionSaving) {
@ -530,142 +519,18 @@ const DocumentContainer: React.FC<DocumentContainerProps> = ({ transactionSaving
prepData],
}
// const dataToSet: DroppedItemsObj = {
// ...droppedItems,
// [key]: [...(droppedItems[key] || []),
// {
// ...prepData,
// radioGroups: dragElemData.label === "radio" ?
// [
// {
// ...prepData,
// dimensions: {
// ...prepData.dimensions, top: 8, left: 10
// }
// },
// {
// ...prepData, dimensions: {
// ...prepData.dimensions,
// top: 8,
// left: 10
// }
// }
// ]
// :
// []
// }],
// }
// if (dragElemData.label === "radio") {
// setDroppedItems(dataToSet);
// } else {
// setDroppedItems(dataToSet);
// }
console.log("data311", dataToSet)
setDroppedItems(dataToSet);
setDroppedItemsCounter((prev) => prev + 1);
setTimeout(() => {
const tagIndex = key in droppedItems ? droppedItems[key].length : 0;
handleTagClick(key, tagIndex)
setSelectedTag({ key, tagIndex })
}, 0)
};
// HANDLE DROP - END
// HANDLE TAG MOUSE DOWN - START
// Updated handleTagMouseDown function with proper group border positioning
const handleTagMouseDown = (event: React.MouseEvent<HTMLDivElement>, key: string, index: number) => {
event.preventDefault();
let targetContainer = event?.currentTarget?.parentElement?.parentElement;
let targetElement = event?.currentTarget?.parentElement;
if (!targetContainer || !targetElement) return;
const containerRect = targetContainer.getBoundingClientRect();
const elementRect = targetElement.getBoundingClientRect();
// Calculate the initial offset (where the mouse was clicked inside the element)
const offsetX = event.clientX - elementRect.left;
const offsetY = event.clientY - elementRect.top;
const conScrollWidth = targetContainer?.scrollWidth;
const conScrollHeight = targetContainer?.scrollHeight;
let isGroupAttr = event.currentTarget.hasAttribute("group");
let groupId = null;
if (isGroupAttr) {
groupId = event.currentTarget.getAttribute("group");
}
let groupElements: NodeListOf<HTMLElement> | null = null;
if (isGroupAttr && groupId) {
groupElements = document.querySelectorAll(`div[group="${groupId}"]`);
// Show initial border position during drag start
handleGroupBorderPosition(groupElements, containerRect, offsetX, offsetY);
}
const handleMouseMove = (event: MouseEvent) => {
// Get new X and Y positions relative to the container
let left = event.clientX - containerRect.left - offsetX;
let top = event.clientY - containerRect.top - offsetY;
// Restrict movement within container bounds
left = Math.max(0, Math.min(left, conScrollWidth - elementRect.width));
top = Math.max(0, Math.min(top, conScrollHeight - elementRect.height));
// Apply the movement to the element first
setDroppedItems(prevState => ({
...prevState,
[key]: Array.isArray(prevState[key])
? prevState[key].map((item, i) =>
i === index ? { ...item, dimensions: { ...item.dimensions, left, top }, update: true } : item
)
: [],
}));
// Update group border position during drag if it's a group element
if (groupElements != null && groupElements.length) {
// Use a small timeout to ensure DOM is updated before recalculating borders
requestAnimationFrame(() => {
handleGroupBorderPosition(groupElements!, containerRect, offsetX, offsetY);
});
}
};
const handleMouseUp = () => {
// CRITICAL: Ensure group borders are properly positioned after drag ends
if (groupElements != null && groupElements.length && groupId) {
// Multiple approaches to ensure the positioning works:
// 1. Immediate update
setTimeout(() => {
handleIGroupBorderPosition(groupId);
}, 10);
// 2. Secondary update to ensure it's properly positioned
setTimeout(() => {
handleIGroupBorderPosition(groupId);
}, 100);
// 3. Final update using requestAnimationFrame for DOM sync
requestAnimationFrame(() => {
setTimeout(() => {
handleIGroupBorderPosition(groupId);
}, 50);
});
}
document.removeEventListener("pointermove", handleMouseMove);
document.removeEventListener("pointerup", handleMouseUp);
};
// Add event listeners
document.addEventListener("pointermove", handleMouseMove);
document.addEventListener("pointerup", handleMouseUp);
};
// HANDLE TAG MOUSE DOWN - END
// HANDLE EXPAND TAG - START
const handleExpandTag = (event: React.MouseEvent<HTMLDivElement>, key: string, index: number) => {
@ -723,99 +588,6 @@ const DocumentContainer: React.FC<DocumentContainerProps> = ({ transactionSaving
};
// HANDLE EXPAND TAG - END
const handleTagClick = (key: string, index: number) => {
setSelectedTag({ key, index })
}
// Updated handleRemoveTag function with your existing API logic and group handling
const handleRemoveTag = (key: string, targetIndex: number) => {
const tag = droppedItems[key][targetIndex];
const recipientId = tag.recipientId;
(async () => {
if ("id" in tag) {
try {
const response = await api.delete(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}/recipients/${recipientId}/tags/${tag.id}`)
if (response.status !== 200) throw "Tag Deletion error"
} catch (err) {
console.error("Tag Deletion error")
return;
}
}
setSelectedTag(null);
// Check if this item has a group for special group handling
if ('group' in tag && tag.group) {
const groupId = tag.group;
// Find all items in the same group
const groupItems = droppedItems[key]
.map((item, idx) => ({ item, index: idx }))
.filter(({ item }) => 'group' in item && item.group === groupId && !item.isDeleted);
// Sort group items by their top position to identify the parent (top-most)
groupItems.sort((a, b) => a.item.dimensions.top - b.item.dimensions.top);
// Check if the item being removed is the parent (top-most item)
const isParentItem = groupItems.length > 0 && groupItems[0].index === targetIndex;
if (isParentItem && groupItems.length > 1) {
// If removing the parent and there are child items, mark all items in the group as deleted
console.log(`Removing parent item and all children for group: ${groupId}`);
// Get indices of all group items to mark as deleted
const indicesToDelete = groupItems.map(({ index }) => index);
setDroppedItems(prevState => ({
...prevState,
[key]: prevState[key].map((item, index) =>
indicesToDelete.includes(index) ? { ...item, isDeleted: true } : item
)
}));
// Remove group border elements after state update
setTimeout(() => {
removeGroupBorders(groupId);
}, 100);
} else {
// If removing a child item or the only item in group, just mark this item as deleted
console.log(`Removing individual item from group: ${groupId}`);
setDroppedItems(prevState => ({
...prevState,
[key]: prevState[key].map((item, index) =>
index === targetIndex ? { ...item, isDeleted: true } : item
)
}));
// Check if this was the last item in the group after state update
setTimeout(() => {
const remainingGroupItems = droppedItems[key].filter(item =>
'group' in item && item.group === groupId && !item.isDeleted
);
if (remainingGroupItems.length === 0) {
// Remove group borders if no items left
removeGroupBorders(groupId);
} else {
// Update group borders for remaining items
handleIGroupBorderPosition(groupId);
}
}, 100);
}
} else {
// Handle non-group item removal (your existing logic)
setDroppedItems(prevState => ({
...prevState,
[key]: prevState[key].map((item, index) =>
index === targetIndex ? { ...item, isDeleted: true } : item
)
}));
}
})()
};
// Helper function to remove group border elements from DOM
const removeGroupBorders = (groupId: string) => {
@ -1070,99 +842,14 @@ const DocumentContainer: React.FC<DocumentContainerProps> = ({ transactionSaving
className='drop-page-in shadow-md relative'
>
{/* DROPPED ITEMS - Render only the dropped items for this specific docId and page - STARTS */}
{droppedItems[key]?.map((item, index) => {
if (item.isDeleted) return;
const type = item.type.toUpperCase();
const IconComponent = typeToIconMap[type] || <FaQuestionCircle />;
const selectedRecipient = selectedRecipients.filter((obj, indx) => obj.id === item.recipientId);
return (
<React.Fragment key={index}>
<div
// key={index}
draggable="false"
className="absolute rounded dropped-item"
onClick={() => handleTagClick(key, index)}
style={{
left: `${item.dimensions.left}px`,
top: `${item.dimensions.top}px`,
width: item.type === "radio" ? `${item.dimensions.width + 20}px` : `${item.dimensions.width}px`,
height: item.type === "radio" ? `max-content` : `${item.dimensions.height}px`
}}
>
{/* If Selected Tag Recipient Info- START */}
{selectedTag?.key && selectedTag.key === key && selectedTag.index === index &&
<div className='absolute flex justify-between items-center w-full max-w-max bg-white top-[-22px] shadow z-20 text-sm rounded-t-sm' >
<div className='flex justify-center items-center gap-1 bg-white px-2 shadow'>
<p className='w-2.5 h-2.5 rounded'
style={{ background: selectedRecipient[0]?.color }}
></p>
<p
className=''>{IconComponent}
</p>
<p className='capitalize text-ellipsis whitespace-nowrap'>{item.label}</p>
<IoMdClose onClick={(e) => {
e.stopPropagation();
handleRemoveTag(key, index)
}} className='cursor-pointer' />
</div>
</div>}
{/* If Selected Tag Recipient Info- END */}
{/* Expand Circle - STARTS */}
{item.type !== "radio" && item.type !== "checkbox" && <div
onPointerDown={(e) => handleExpandTag(e, key, index)}
className='w-2.5 h-2.5 absolute bg-red-400 rounded-full bottom-[-8px] right-[-8px] cursor-nw-resize hover:bg-blue-400'>
</div>}
{/* Expand Circle - ENDS */}
{/* Tag - START */}
{
<div
{...("group" in item && item.group ? { "group": item.group } : {})}
onPointerDown={(e) => handleTagMouseDown(e, key, index)}
className='p-2 rounded-sm h-full shadow opacity-40 cursor-grab w-full'
style={{ background: selectedRecipient[0]?.color }}
>
<p
className={`flex justify-center items-center w-full text-xl text-white h-full`}
// style={{ color: selectedRecipients[item.recipientIndx]?.color }}
>
{IconComponent}
</p>
</div>
}
{/* Tag - END */}
</div>
<>
{
"group" in item && item.group && "isGroupExist" in item && !item.isGroupExist &&
<>
<div className="group-border" border-group={item.group} border-pos="top"></div>
<div className="group-border" border-group={item.group} border-pos="right"></div>
<div className="group-border bottom-border" border-group={item.group} border-pos="bottom">
<div onClick={() => handleAddGroupItemClicked(key, item)}><IoAdd /></div>
</div>
<div className="group-border" border-group={item.group} border-pos="left"></div>
</>
}
</>
</React.Fragment>
)
}
)}
{/* Render only the dropped items for this specific docId and page - ENDS */}
<DroppedItemsTagsCon
droppedItems={droppedItems}
key={key}
selectedTag={selectedTag}
setSelectedTag={setSelectedTag}
accountId={accountId}
transaction
/>
<img
style={{ "minWidth": page.width, "minHeight": page.height, "maxWidth": page.width, "maxHeight": page.height }}

View File

@ -0,0 +1,313 @@
// Functions - START
// handleTagClick
import React from 'react'
import { DroppedItemsObj } from './DocumentContainer';
import typeToIconMap from '../../../helper/iconMap';
import { IoMdClose } from 'react-icons/io';
import { IoAdd } from 'react-icons/io5';
import { DroppedItem } from '../../../utlity/types';
import { FaQuestionCircle } from 'react-icons/fa';
import api from '../../../config/api';
interface DroppedItemsTagsConProps {
droppedItems: DroppedItemsObj;
key: string;
selectedTag: DroppedItem
setSelectedTag: React.Dispatch<React.SetStateAction<DroppedItem>>;
setDroppedItems: React.Dispatch<React.SetStateAction<DroppedItemsObj>>;
}
const DroppedItemsTagsCon: React.FC<DroppedItemsTagsConProps> = ({ droppedItems, key, selectedTag, setSelectedTag }) => {
const handleTagClick = (key: string, index: number) => {
setSelectedTag({ key, index })
}
const handleRemoveTag = (key: string, targetIndex: number) => {
const tag = droppedItems[key][targetIndex];
const recipientId = tag.recipientId;
(async () => {
if ("id" in tag) {
try {
const response = await api.delete(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}/recipients/${recipientId}/tags/${tag.id}`)
if (response.status !== 200) throw "Tag Deletion error"
} catch (err) {
console.error("Tag Deletion error")
return;
}
}
setSelectedTag(null);
// Check if this item has a group for special group handling
if ('group' in tag && tag.group) {
const groupId = tag.group;
// Find all items in the same group
const groupItems = droppedItems[key]
.map((item, idx) => ({ item, index: idx }))
.filter(({ item }) => 'group' in item && item.group === groupId && !item.isDeleted);
// Sort group items by their top position to identify the parent (top-most)
groupItems.sort((a, b) => a.item.dimensions.top - b.item.dimensions.top);
// Check if the item being removed is the parent (top-most item)
const isParentItem = groupItems.length > 0 && groupItems[0].index === targetIndex;
if (isParentItem && groupItems.length > 1) {
// If removing the parent and there are child items, mark all items in the group as deleted
console.log(`Removing parent item and all children for group: ${groupId}`);
// Get indices of all group items to mark as deleted
const indicesToDelete = groupItems.map(({ index }) => index);
setDroppedItems(prevState => ({
...prevState,
[key]: prevState[key].map((item, index) =>
indicesToDelete.includes(index) ? { ...item, isDeleted: true } : item
)
}));
// Remove group border elements after state update
setTimeout(() => {
removeGroupBorders(groupId);
}, 100);
} else {
// If removing a child item or the only item in group, just mark this item as deleted
console.log(`Removing individual item from group: ${groupId}`);
setDroppedItems(prevState => ({
...prevState,
[key]: prevState[key].map((item, index) =>
index === targetIndex ? { ...item, isDeleted: true } : item
)
}));
// Check if this was the last item in the group after state update
setTimeout(() => {
const remainingGroupItems = droppedItems[key].filter(item =>
'group' in item && item.group === groupId && !item.isDeleted
);
if (remainingGroupItems.length === 0) {
// Remove group borders if no items left
removeGroupBorders(groupId);
} else {
// Update group borders for remaining items
handleIGroupBorderPosition(groupId);
}
}, 100);
}
} else {
// Handle non-group item removal (your existing logic)
setDroppedItems(prevState => ({
...prevState,
[key]: prevState[key].map((item, index) =>
index === targetIndex ? { ...item, isDeleted: true } : item
)
}));
}
})()
};
// HANDLE TAG MOUSE DOWN - START
// Updated handleTagMouseDown function with proper group border positioning
const handleTagMouseDown = (event: React.MouseEvent<HTMLDivElement>, key: string, index: number) => {
event.preventDefault();
let targetContainer = event?.currentTarget?.parentElement?.parentElement;
let targetElement = event?.currentTarget?.parentElement;
if (!targetContainer || !targetElement) return;
const containerRect = targetContainer.getBoundingClientRect();
const elementRect = targetElement.getBoundingClientRect();
// Calculate the initial offset (where the mouse was clicked inside the element)
const offsetX = event.clientX - elementRect.left;
const offsetY = event.clientY - elementRect.top;
const conScrollWidth = targetContainer?.scrollWidth;
const conScrollHeight = targetContainer?.scrollHeight;
let isGroupAttr = event.currentTarget.hasAttribute("group");
let groupId = null;
if (isGroupAttr) {
groupId = event.currentTarget.getAttribute("group");
}
let groupElements: NodeListOf<HTMLElement> | null = null;
if (isGroupAttr && groupId) {
groupElements = document.querySelectorAll(`div[group="${groupId}"]`);
// Show initial border position during drag start
handleGroupBorderPosition(groupElements, containerRect, offsetX, offsetY);
}
let timeOut = null
const handleMouseMove = (event: MouseEvent) => {
// Get new X and Y positions relative to the container
let left = event.clientX - containerRect.left - offsetX;
let top = event.clientY - containerRect.top - offsetY;
// Restrict movement within container bounds
left = Math.max(0, Math.min(left, conScrollWidth - elementRect.width));
top = Math.max(0, Math.min(top, conScrollHeight - elementRect.height));
// Apply the movement to the element first
setDroppedItems(prevState => ({
...prevState,
[key]: Array.isArray(prevState[key])
? prevState[key].map((item, i) =>
i === index ? { ...item, dimensions: { ...item.dimensions, left, top }, update: true } : item
)
: [],
}));
// Update group border position during drag if it's a group element
if (groupElements != null && groupElements.length) {
// Use a small timeout to ensure DOM is updated before recalculating borders
requestAnimationFrame(() => {
handleGroupBorderPosition(groupElements!, containerRect, offsetX, offsetY);
});
}
};
const handleMouseUp = () => {
// CRITICAL: Ensure group borders are properly positioned after drag ends
if (groupElements != null && groupElements.length && groupId) {
// Multiple approaches to ensure the positioning works:
// 1. Immediate update
setTimeout(() => {
handleIGroupBorderPosition(groupId);
}, 10);
// 2. Secondary update to ensure it's properly positioned
setTimeout(() => {
handleIGroupBorderPosition(groupId);
}, 100);
// 3. Final update using requestAnimationFrame for DOM sync
requestAnimationFrame(() => {
setTimeout(() => {
handleIGroupBorderPosition(groupId);
}, 50);
});
}
document.removeEventListener("pointermove", handleMouseMove);
document.removeEventListener("pointerup", handleMouseUp);
};
// Add event listeners
document.addEventListener("pointermove", handleMouseMove);
document.addEventListener("pointerup", handleMouseUp);
};
// HANDLE TAG MOUSE DOWN - END
return (
<>
{/* DROPPED ITEMS - Render only the dropped items for this specific docId and page - STARTS */}
{droppedItems[key]?.map((item, index) => {
if (item.isDeleted) return;
const type = item.type.toUpperCase();
const IconComponent = typeToIconMap[type] || <FaQuestionCircle />;
const selectedRecipient = selectedRecipients.filter((obj, indx) => obj.id === item.recipientId);
return (
<React.Fragment key={index}>
<div
// key={index}
draggable="false"
className="absolute rounded dropped-item"
onClick={() => handleTagClick(key, index)}
style={{
left: `${item.dimensions.left}px`,
top: `${item.dimensions.top}px`,
width: item.type === "radio" ? `${item.dimensions.width + 20}px` : `${item.dimensions.width}px`,
height: item.type === "radio" ? `max-content` : `${item.dimensions.height}px`
}}
>
{/* If Selected Tag Recipient Info- START */}
{selectedTag?.key && selectedTag.key === key && selectedTag.index === index &&
<div className='absolute flex justify-between items-center w-full max-w-max bg-white top-[-22px] shadow z-20 text-sm rounded-t-sm' >
<div className='flex justify-center items-center gap-1 bg-white px-2 shadow'>
<p className='w-2.5 h-2.5 rounded'
style={{ background: selectedRecipient[0]?.color }}
></p>
<p
className=''>{IconComponent}
</p>
<p className='capitalize text-ellipsis whitespace-nowrap'>{item.label}</p>
<IoMdClose onClick={(e) => {
e.stopPropagation();
handleRemoveTag(key, index)
}} className='cursor-pointer' />
</div>
</div>}
{/* If Selected Tag Recipient Info- END */}
{/* Expand Circle - STARTS */}
{item.type !== "radio" && item.type !== "checkbox" && <div
onPointerDown={(e) => handleExpandTag(e, key, index)}
className='w-2.5 h-2.5 absolute bg-red-400 rounded-full bottom-[-8px] right-[-8px] cursor-nw-resize hover:bg-blue-400'>
</div>}
{/* Expand Circle - ENDS */}
{/* Tag - START */}
{
<div
{...("group" in item && item.group ? { "group": item.group } : {})}
onPointerDown={(e) => handleTagMouseDown(e, key, index)}
className='p-2 rounded-sm h-full shadow opacity-40 cursor-grab w-full'
style={{ background: selectedRecipient[0]?.color }}
>
<p
className={`flex justify-center items-center w-full text-xl text-white h-full`}
// style={{ color: selectedRecipients[item.recipientIndx]?.color }}
>
{IconComponent}
</p>
</div>
}
{/* Tag - END */}
</div>
<>
{
"group" in item && item.group && "isGroupExist" in item && !item.isGroupExist &&
<>
<div className="group-border" border-group={item.group} border-pos="top"></div>
<div className="group-border" border-group={item.group} border-pos="right"></div>
<div className="group-border bottom-border" border-group={item.group} border-pos="bottom">
<div
onClick={() => handleAddGroupItemClicked(key, item)}>
<IoAdd />
</div>
</div>
<div className="group-border" border-group={item.group} border-pos="left"></div>
</>
}
</>
</React.Fragment>
)
}
)}
{/* Render only the dropped items for this specific docId and page - ENDS */}
</>
)
}
export default DroppedItemsTagsCon

View File

@ -155,7 +155,7 @@ const LeftSideBar: React.FC<LeftSideBarProps> = ({ isFields, selectedRecipientIn
document.pages != undefined && <img
key={indx}
className='rounded-sm shadow'
src={document.pages[0].src}
src={"data:image/png;base64," + document.thumbnail}
alt="" />
}

View File

@ -128,10 +128,10 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
setTimeout(() => {
if (transactionTemplateToggle === TRANSACTION_TEMPLATE_TOGGLE.TRANSACTIONS) {
if (isSignSend) {
window.open(`./../../../sign/${selfUserSign.recipientId}`, "_self");
// window.open(`./../../../sign/${selfUserSign.recipientId}`, "_self");
}
else {
navigate(`/document-completion-screen/${accountId}/${transactionId}`, { replace: true })
// navigate(`/document-completion-screen/${accountId}/${transactionId}`, { replace: true })
}
} else {
navigate(`/templates`);
@ -169,25 +169,6 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
zoom(Number(indx), 'zoom-con')
}, [selFitIndx])
// useEffect(() => {
// let timeoutId: number;
// const timeOutIn = 8000;
// const updateLabel = () => {
// if (document.visibilityState === 'visible') {
// setTransactionSaving(true);
// setTimeout(() => {
// setTransactionSaving(false);
// }, 4000)
// }
// timeoutId = setTimeout(updateLabel, timeOutIn);
// };
// timeoutId = setTimeout(updateLabel, timeOutIn);
// // Cleanup on unmount
// return () => clearTimeout(timeoutId);
// }, []);
useEffect(() => {
if (!transactionSaving) return;
@ -223,16 +204,6 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
<p className='tracking-wide'>Pages</p>
</div>
{/* <div className='flex items-center gap-1 cursor-pointer text-xs px-2 py-1 rounded-sm'>
<RiResetLeftLine />
<p className='tracking-wide'>Reset</p>
</div> */}
{/* <div className='flex items-center gap-1 cursor-pointer text-xs px-2 py-1 rounded-sm'>
<p className='tracking-wide'>Fit</p>
<MdKeyboardArrowDown />
</div> */}
<div
tabIndex={1}
onBlur={() => setIsFitDd(false)}

View File

@ -1,21 +0,0 @@
import React from 'react'
interface LabelAttrInt {
label: string;
handlePropertyChange: (changeTo: string, changeWith: string | boolean | number) => void;
}
const LabelAttr: React.FC<LabelAttrInt> = ({ label, handlePropertyChange }) => {
return (
<div className="flex flex-col">
<label htmlFor="" className="">Label</label>
<input
value={label}
onChange={(e) => handlePropertyChange('label', e.target.value)}
type="text"
className="outline-none border-1 rounded px-2 py-1 border-slate-200" />
</div>
)
}
export default LabelAttr

View File

@ -1,31 +1,23 @@
import { DroppedItemsObj } from "../DocumentContainer";
import React, { useEffect, useState } from "react";
import { dateFormats, dateTimeFormats, timeFormats } from "../../../../utlity/dateTimeFormats";
import { DroppedItem, StylesInterface } from "../../../../utlity/types";
import { IoIosArrowDown } from "react-icons/io";
import { TagsTypes } from "../../../../utlity/types";
import LabelAttr from "./LabelAttr";
import RequiredAttr from "./RequiredAttr";
import CurrTimeStampAttr from "./currTimeStampAttr";
import CommonAttrDropDown from "./CommonAttrDropDown";
import MaskTypePassAttr from "./MaskTypePassAttr";
import TemporalDateAttr from "./TemporalDateAttr";
import SelectTagAttr from "./SelectTagAttr";
import MaxMinLenAttr from "./MaxMinLenAttr";
import RecipientsAttrCon from "./RecipientsAttrCon";
import MovableFieldContainer from "./MovableField";
import DirectionalControls from "./DirectionalControls";
import TextValueFIll from "./TextValueFIll";
// interface DirectionalControlsProps {
// onMove: (direction: 'up' | 'down' | 'left' | 'right') => void;
// disabled?: boolean;
// stepSize?: number;
// className?: string;
// }
import LabelAttr from "./attributes/LabelAttr";
import RequiredAttr from "./attributes/RequiredAttr";
import CommonAttrDropDown from "./attributes/CommonAttrDropDown";
import MaskTypePassAttr from "./attributes/MaskTypePassAttr";
import TemporalDateAttr from "./attributes/TemporalDateAttr";
import SelectTagAttr from "./attributes/SelectTagAttr";
import MaxMinLenAttr from "./attributes/MaxMinLenAttr";
import RecipientsAttrCon from "./attributes/RecipientsAttrCon";
import DirectionalControls from "./attributes/DirectionalControls";
import TextValueFIll from "./attributes/TextValueFIll";
import CurrTimeStampAttr from "./attributes/CurrTimeStampAttr";
import ToolTipAttr from "./attributes/ToolTipAttr";
export interface DroppedItemProps {
droppedItems: DroppedItem[]
@ -34,12 +26,6 @@ export interface DroppedItemProps {
selTagKey: string,
selTagIndx: number,
signClient: boolean,
// DirectionalControlsProps: {
// onMove: (direction: 'up' | 'down' | 'left' | 'right', stepSize?: number) => void;
// disabled?: boolean;
// stepSize?: number;
// className?: string;
// }
}
export enum TEXT {
@ -118,121 +104,6 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
const handlePropertyChange = (changeTo: string, changeWith: string | boolean | number | StylesInterface, is24Hrs = null) => {
if (changeTo === '') return
// if (changeTo === "subType" && typeof changeWith === "string" && changeWith.toLowerCase() === "password") {
// if (!signClient) {
// setDroppedItems((prev) => (
// {
// ...prev,
// [selTagKey]: Array.isArray(prev[selTagKey])
// ? prev[selTagKey].map((item, i) =>
// i === selTagIndx ? { ...item, [changeTo]: changeWith, maskType: "All", maskCharacter: "ASTERISK", update: true } : item
// )
// : [],
// }
// ));
// } else {
// setDroppedItems((prev) => {
// const updated = [...prev];
// updated[selTagIndx] = { ...updated[selTagIndx], [changeTo]: changeWith, maskType: "All", maskCharacter: "ASTERISK", update: true }
// return updated;
// })
// }
// } else if (changeTo === "subType" && (changeWith === NUMBER.CURRENCY || changeWith === NUMBER.INTEGER || changeWith === NUMBER.DECIMAL)) {
// let decPlace = changeWith !== NUMBER.DECIMAL ? 0 : decimalPlace;
// const isCurrency = changeWith === NUMBER.CURRENCY;
// // const currencyType = null
// if (!signClient) {
// setDroppedItems((prev) => (
// {
// ...prev,
// [selTagKey]: Array.isArray(prev[selTagKey]) // Ensure it's an array
// ? prev[selTagKey].map((item, i) =>
// i === selTagIndx ? { ...item, [changeTo]: changeWith, decimalPlace: decPlace, isCurrency, update: true } : item
// )
// : [],
// }// Provide a fallback in case it's undefined or not an array
// ));
// } else {
// setDroppedItems((prev) => {
// const updated = [...prev];
// updated[selTagIndx] = { ...updated[selTagIndx], [changeTo]: changeWith, decimalPlace: decPlace, isCurrency, update: true }
// return updated;
// })
// }
// }
// else if (changeTo === "format" && selectedTag.subType === TEMPORAL.DATE_TIME) {
// let val = timeFormats[0].format;
// if (is24Hrs === null) {
// val = timeFormats[0].format
// } else if (!is24Hrs) {
// val = timeFormats[1].format
// } else {
// val = timeFormats[0].format
// }
// // console.log("val", val, is24Hrs)
// // if(is24Hrs === null) {
// // changeWith = changeWith + " " + val;
// // }
// if (!signClient) {
// setDroppedItems((prev) => {
// const updatedArray = Array.isArray(prev[selTagKey])
// ? prev[selTagKey].map((item, i) => {
// if (i === selTagIndx) {
// const updatedItem = { ...item, [changeTo]: changeWith + " " + val, update: true };
// console.log('Updating item at index', i, 'with:', updatedItem);
// return updatedItem;
// }
// return item;
// })
// : [];
// return {
// ...prev,
// [selTagKey]: updatedArray,
// };
// });
// } else {
// setDroppedItems((prev) => {
// const updated = [...prev];
// updated[selTagIndx] = { ...updated[selTagIndx], [changeTo]: changeWith + " " + val, update: true }
// return updated;
// })
// }
// }
// else {
// if (!signClient) {
// setDroppedItems((prev) => {
// const updatedItems = Array.isArray(prev[selTagKey])
// ? prev[selTagKey].map((item, i) =>
// i === selTagIndx ? { ...item, [changeTo]: changeWith, update: true } : item
// )
// : [];
// return {
// ...prev,
// [selTagKey]: updatedItems,
// };
// });
// } else {
// setDroppedItems((prev) => {
// const updated = [...prev];
// updated[selTagIndx] = { ...updated[selTagIndx], [changeTo]: changeWith, update: true }
// return updated;
// })
// }
// }
if (!signClient) {
setDroppedItems((prev) => {
@ -266,22 +137,6 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
setDropDownToggle(null)
}
// useEffect(() => {
// if (selectedTag.dateFormat === TEMPORAL.DATE || selectedTag.dateFormat === TEMPORAL.DATE_TIME || selectedTag.dateFormat === TEMPORAL.TIME) {
// if (selectedTag.dateFormat === TEMPORAL.DATE) {
// handlePropertyChange("format", dateFormats[0].format)
// }
// else if (selectedTag.dateFormat === TEMPORAL.DATE_TIME) {
// handlePropertyChange("format", dateTimeFormats[0].format)
// }
// else if (selectedTag.dateFormat === TEMPORAL.TIME) {
// handlePropertyChange("format", timeFormats[0].format)
// }
// }
// }, [selectedTag.dateFormat])
useEffect(() => {
if (selectedTag.label === "temporal" && !("dateFormat" in selectedTag)) {
handlePropertyChange("dateFormat", TEMPORAL.DATE);
@ -305,24 +160,6 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
setDecimalPlace(selectedTag.decimalPlace ?? 0)
}, [selectedTag.decimalPlace ?? 0])
// useEffect(() => {
// if ("styles" in selectedTag) {
// console.log("styles" in selectedTag)
// const fontSize = selectedTag?.styles?.textSize;
// const tagHeight = selectedTag?.dimensions?.height - 18;
// console.log(fontSize)
// if (selectedTag.subType !== TEXT.PASSWORD && selectedTag.subType !== TEXT.PARAGRAPH && tagHeight > (fontSize + fontSize)) {
// handlePropertyChange("subType", TEXT.PARAGRAPH)
// } else if (selectedTag.subType !== TEXT.PASSWORD && selectedTag.subType !== TEXT.SINGLE_LINE && tagHeight <= (fontSize + fontSize)) {
// console.log("Change subType Called from elseif")
// handlePropertyChange("subType", TEXT.SINGLE_LINE)
// }
// }
// }, [selectedTag])
useEffect(() => {
if (!selectedTag) return;
@ -333,26 +170,6 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
setStyles({ ...defaultStyles, ...selectedTag.styles });
}
// Optional subType logic
// const fontSize = selectedTag?.styles?.textSize || defaultStyles.textSize;
// const tagHeight = selectedTag?.dimensions?.height - 18;
// if (
// selectedTag.type === TagsTypes.TEXT &&
// selectedTag.subType !== TEXT.PASSWORD &&
// selectedTag.subType !== TEXT.PARAGRAPH &&
// tagHeight > fontSize * 2
// ) {
// handlePropertyChange("subType", TEXT.PARAGRAPH);
// } else if (
// selectedTag.subType !== TEXT.PASSWORD &&
// selectedTag.subType !== TEXT.SINGLE_LINE &&
// tagHeight <= fontSize * 2
// ) {
// handlePropertyChange("subType", TEXT.SINGLE_LINE);
// }
}, [selectedTag]);
const handleStyleChange = (key, value) => {
@ -472,28 +289,22 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
<>
{/* Right Side Bar Start */}
<div className='col-span-2 w-full h-full bg-white text-sm overflow-y-auto'>
<p className="p-2 font-semibold text-md">Properties</p>
<p className="p-2 font-semibold text-md"><span className="capitalize">{selectedTag.type.toLowerCase()}</span> Attributes:</p>
<hr className="text-slate-200" />
<div className="p-3 text-sm text-slate-600 flex flex-col gap-2">
{
<RecipientsAttrCon selectedRecipientId={selectedTag.recipientId} handlePropertyChange={handlePropertyChange} />
}
<RecipientsAttrCon selectedRecipientId={selectedTag.recipientId} handlePropertyChange={handlePropertyChange} />
<DirectionalControls {...DirectionalControlsProps} selectedType={selectedTag.dimensions} />
{selectedTag.label &&
<LabelAttr label={selectedTag.label} handlePropertyChange={handlePropertyChange} />}
{(selectedTag.type !== TagsTypes.SIGNATURE && selectedTag.type !== TagsTypes.INITIALS) &&
<>
<RequiredAttr required={selectedTag.required ? selectedTag.required : false} handlePropertyChange={handlePropertyChange} />
</>
<ToolTipAttr tooltip={selectedTag.tooltip ?? ""} handlePropertyChange={handlePropertyChange} />
{
(selectedTag.type !== TagsTypes.SIGNATURE && selectedTag.type !== TagsTypes.INITIALS) &&
<RequiredAttr required={selectedTag.required ? selectedTag.required : false} handlePropertyChange={handlePropertyChange} />
}
{selectedTag.type.toLowerCase() === TagsTypes.TEMPORAL &&
@ -575,9 +386,6 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
<MaxMinLenAttr maxLength={selectedTag.maxLength} minLength={selectedTag.minLength} handlePropertyChange={handlePropertyChange} />
}
{(selectedTag.type.toLowerCase() !== TagsTypes.SIGNATURE && selectedTag.type.toLowerCase() !== TagsTypes.INITIALS) &&
<div className="">
<div className="flex items-center justify-between mr-2 cursor-pointer"

View File

@ -1,8 +1,8 @@
import { MdKeyboardArrowDown } from 'react-icons/md';
import { DROPDOWNTOGGLE, MASKCHARACTER, MASKTYPE, NUMBER, SELECT, TEMPORAL, TEXT } from './RightSideBar';
import { DroppedItem, TagsTypes } from '../../../../utlity/types';
import { dateFormats, timeFormats } from '../../../../utlity/dateTimeFormats';
import { DROPDOWNTOGGLE, MASKCHARACTER, MASKTYPE, NUMBER, SELECT, TEMPORAL, TEXT } from '../RightSideBar';
import { DroppedItem, TagsTypes } from '../../../../../utlity/types';
import { dateFormats, timeFormats } from '../../../../../utlity/dateTimeFormats';
import { FaCommentsDollar } from 'react-icons/fa';
interface CommonAttrDropDownInt {

View File

@ -148,83 +148,13 @@ const DirectionalControls: React.FC<DirectionalControlsProps> = ({
</button>
</div>
{/* Bottom */}
<button type="button" onClick={() => handleMove('down')} disabled={disabled} className={buttonClass} title="Move Down">
<FaArrowDown />
</button>
{/* Middle Row: Left - Center (Inputs) - Right */}
<div className="flex items-center space-x-1">
{/* Left Button */}
{/* <div className="flex flex-col items-center">
<button
onClick={() => handleMove('left')}
disabled={disabled}
className={buttonClass}
title="Move left"
type="button"
>
<FaArrowLeft size={12} />
</button>
<span className="mt-1">Left</span>
</div> */}
{/* Center Panel */}
<div className="relative flex items-center justify-center bg-white rounded-lg px-1 py-2 w-24 ">
{/* Floating dimensions tooltip */}
{/* <div className="absolute -top-2 left-1/2 -translate-x-1/2 px-2 py-[1px] text-[10px] font-mono text-black z-10 rounded-sm flex items-center gap-[2px]">
<input
type="number"
value={leftValue}
onChange={(e) => handlePositionInputChange('left', e.target.value)}
onBlur={() => handlePositionInputBlur('left')}
onKeyPress={(e) => handleKeyPress(e, 'left')}
disabled={disabled}
className="w-[40px] h-[16px] text-[10px] text-center border-none focus:outline-none text-black font-mono"
/>
<span className="mx-[1px]">×</span>
<input
type="number"
value={topValue}
onChange={(e) => handlePositionInputChange('top', e.target.value)}
onBlur={() => handlePositionInputBlur('top')}
onKeyPress={(e) => handleKeyPress(e, 'top')}
disabled={disabled}
className="w-[40px] h-[16px] text-[10px] text-center border-none focus:outline-none text-black font-mono"
/>
</div> */}
</div>
{/* Right Button */}
{/* <div className="flex flex-col items-center">
<button
onClick={() => handleMove('right')}
disabled={disabled}
className={buttonClass}
title="Move right"
type="button"
>
<FaArrowRight size={12} />
</button>
<span className="mt-1">Right</span>
</div> */}
</div>
{/* Bottom Button */}
{/* <div className="flex justify-center me-4">
<div className="flex flex-col items-center">
<button
onClick={() => handleMove('down')}
disabled={disabled}
className={buttonClass}
title="Move down"
type="button"
>
<FaArrowDown size={12} />
</button>
<span className="mt-1">Bottom</span>
</div>
</div> */}
</div>
);
};

View File

@ -0,0 +1,23 @@
import React from 'react'
interface LabelAttrInt {
label: string;
handlePropertyChange: (changeTo: string, changeWith: string | boolean | number) => void;
}
const LabelAttr: React.FC<LabelAttrInt> = ({ label, handlePropertyChange }) => {
return (
<>
<div className="flex flex-col">
<label>Label</label>
<input
value={label}
onChange={(e) => handlePropertyChange('label', e.target.value)}
type="text"
className="outline-none border-1 rounded px-2 py-1 border-slate-200" />
</div>
</>
)
}
export default LabelAttr

View File

@ -1,5 +1,5 @@
import { MdKeyboardArrowDown } from "react-icons/md";
import { DROPDOWNTOGGLE, MASKCHARACTER, MASKTYPE } from "./RightSideBar";
import { DROPDOWNTOGGLE, MASKCHARACTER, MASKTYPE } from "../RightSideBar";
import { LuAsterisk } from "react-icons/lu";
import { GoDotFill } from "react-icons/go";
import { IoClose } from "react-icons/io5";

View File

@ -2,8 +2,8 @@ import React, { useEffect, useState } from 'react'
import { IoCheckmark } from 'react-icons/io5';
import { MdKeyboardArrowDown } from 'react-icons/md';
import { useSelector } from 'react-redux';
import { RootState } from '../../../../store/store';
import { recipientType } from '../../../../store/slices/selectedRecipientsSlice';
import { RootState } from '../../../../../store/store';
import { recipientType } from '../../../../../store/slices/selectedRecipientsSlice';
interface SelectedRecipientsIntr {

View File

@ -1,9 +1,9 @@
import { useEffect, useState } from "react";
import { dateFormats, dateTimeFormats, monthFormats, timeFormats, weekFormats, yearFormats } from "../../../../utlity/dateTimeFormats";
import { DROPDOWNTOGGLE, TEMPORAL } from "./RightSideBar";
import { dateFormats, dateTimeFormats, monthFormats, timeFormats, weekFormats, yearFormats } from "../../../../../utlity/dateTimeFormats";
import { DROPDOWNTOGGLE, TEMPORAL } from "../RightSideBar";
import { MdKeyboardArrowDown } from "react-icons/md";
import dayjs from "dayjs";
import { DroppedItem } from "../../../../utlity/types";
import { DroppedItem } from "../../../../../utlity/types";
const dateTimeFormatMap = {
"date": dateFormats,

View File

@ -0,0 +1,23 @@
import React from 'react'
interface ToolTipAttrInt {
tooltip: string;
handlePropertyChange: (changeTo: string, changeWith: string | boolean | number) => void;
}
const ToolTipAttr: React.FC<ToolTipAttrInt> = ({ tooltip, handlePropertyChange }) => {
return (
<>
<div className="flex flex-col">
<label>ToolTip</label>
<input
value={tooltip}
onChange={(e) => handlePropertyChange('tooltip', e.target.value)}
type="text"
className="outline-none border-1 rounded px-2 py-1 border-slate-200" />
</div>
</>
)
}
export default ToolTipAttr

View File

@ -81,18 +81,29 @@ export const uploadDocuments = createAsyncThunk<
};
const toggle = state.selectedRecipients.transactionTemplateToggle;
const response = await api.post(
`/api/accounts/${accountId}/${toggle}/${transactionId}/documents`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
);
let response = [];
// debugger
for (let i = 0; i < formData.getAll("file").length; i++) {
const file = new FormData();
file.append("file", formData.getAll("file")[i]);
const res = await api.post(
`/api/accounts/${accountId}/${toggle}/${transactionId}/documents`,
file,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
);
console.log(res.data);
response.push(res.data);
}
// await sleep(5000);
dispatch(hideLoader());
return [response.data];
return [...response];
} catch (error: any) {
dispatch(hideLoader());
@ -160,7 +171,9 @@ const documentsSlice = createSlice({
})
.addCase(uploadDocuments.fulfilled, (state, action: PayloadAction<Document[]>) => {
state.loading = false;
state.documents.push(...action.payload);
action.payload.forEach((doc, indx) => {
state.documents.push(doc);
});
})
.addCase(uploadDocuments.rejected, (state, action) => {
state.loading = false;

View File

@ -1,335 +1,3 @@
// import { createSlice, PayloadAction } from '@reduxjs/toolkit';
// import { createAsyncThunk } from '@reduxjs/toolkit';
// import { toast } from 'react-toastify';
// import colors from '../../utlity/colorsArr';
// import api from '../../config/api';
// export enum recipientType {
// SIGNER = "Signer",
// INPERSONSIGNER = "InPersonSigner",
// CC = "CC"
// }
// export interface Recipient {
// id?: string;
// firstName: string;
// lastName: string;
// routingOrder: number;
// email: string;
// hostName: string;
// hostEmail: string;
// type: recipientType;
// color?: string;
// }
// export interface SelectedRecipientInt {
// recipients: Recipient[],
// signingOrder: boolean,
// transactionTemplateToggle: TRANSACTION_TEMPLATE_TOGGLE
// }
// interface AddRecipientArgs {
// recipientsData: Recipient[];
// accountId: string;
// transactionId: string;
// }
// export enum TRANSACTION_TEMPLATE_TOGGLE {
// TRANSACTIONS = "transactions",
// TEMPLATES = "templates"
// }
// const initialState: SelectedRecipientInt = {
// recipients: [],
// signingOrder: false,
// transactionTemplateToggle: TRANSACTION_TEMPLATE_TOGGLE.TRANSACTIONS
// };
// export const addRecipientAsync = createAsyncThunk<Recipient[], AddRecipientArgs>(
// 'selectedRecipients/addRecipientAsync',
// async ({ recipientsData, accountId, transactionId }, { rejectWithValue }) => {
// console.log(recipientsData, accountId, transactionId, "recipientsData Line 46");
// try {
// console.log(recipientsData, "recipientsData --- Line 48");
// const updateRecipientsData = recipientsData.filter((recipient, idx) => recipient.id !== null);
// const createRecipientsData = recipientsData.filter((recipient, idx) => recipient.id == null);
// console.log(updateRecipientsData, "updateRecipientsData Line 52");
// console.log(createRecipientsData, "createRecipientsData Line 53");
// const resUpdate = await api.put(
// `/api/accounts/${accountId}/transactions/${transactionId}/recipients`,
// updateRecipientsData
// );
// const resCreate = await api.post(
// `/api/accounts/${accountId}/transactions/${transactionId}/recipients`,
// createRecipientsData
// );
// if (createRecipientsData.length === 0) resCreate.data = [];
// if (updateRecipientsData.length === 0) resUpdate.data = [];
// console.log(resCreate, "resCreate");
// console.log(resUpdate, "resUpdate");
// return [...resCreate.data, ...resUpdate.data] as Recipient[];
// } catch (err: any) {
// return rejectWithValue(err.response?.data || "Failed to add recipient");
// }
// }
// );
// interface RemoveRecipientAsyncInterfaceObj {
// id?: string;
// email?: string;
// }
// interface RemoveRecipientAsyncInterface {
// recipientId: number | null;
// accountId: string;
// transactionId: string;
// email: string;
// }
// export const removeRecipientAsync = createAsyncThunk<string | number, RemoveRecipientAsyncInterface>(
// 'selectedRecipients/removeRecipientAsync',
// async (obj, { rejectWithValue }) => {
// try {
// if (obj.recipientId) {
// const res = await api.delete(`/api/accounts/${obj.accountId}/transactions/${obj.transactionId}/recipients/${obj.recipientId}`);
// console.log(res, "Line 77")
// return obj.recipientId;
// }
// return obj.email
// } catch (err: any) {
// return rejectWithValue("Failed to remove recipient");
// }
// }
// );
// export const fetchRecipients = createAsyncThunk<Recipient[], { accountId: string, transactionId: string }>(
// 'selectedRecipients/fetchRecipients',
// async ({ accountId, transactionId }, { rejectWithValue }) => {
// try {
// const response = await api.get(`/api/accounts/${accountId}/transactions/${transactionId}/recipients`);
// return response.data as Recipient[];
// } catch (err: any) {
// return rejectWithValue(err.response?.data || "Failed to fetch recipients");
// }
// }
// );
// const selectedRecipientsSlice = createSlice({
// name: 'selectedRecipients',
// initialState,
// reducers: {
// // Add a single recipient
// addRecipient: (state, action: PayloadAction<Recipient>) => {
// for (const recipient of state.recipients) {
// if (recipient.email === action.payload.email) {
// toast.dismiss();
// toast.error("Email already exists !", {
// position: "bottom-right",
// autoClose: 5000,
// hideProgressBar: false,
// closeOnClick: false,
// pauseOnHover: true,
// draggable: true,
// progress: undefined,
// theme: "light",
// });
// return state;
// }
// }
// // Adding Recipient on top if type is inPersonSigner
// console.log("Getting Type ", action.payload.type)
// if (action.payload.type === recipientType.INPERSONSIGNER) {
// state.signingOrder = true
// state.recipients = [action.payload, ...state.recipients]
// } else {
// state.recipients.push(action.payload);
// }
// },
// resetRecipients: (state) => {
// state.recipients = [];
// },
// toggleToTemplates: (state) => {
// state.transactionTemplateToggle = TRANSACTION_TEMPLATE_TOGGLE.TEMPLATES;
// },
// // Replace the entire selectedRecipients array
// setSelectedRecipients: (state, action: PayloadAction<Recipient[]>) => {
// for (const [index, recipient] of action.payload.entries()) {
// if ((recipient.type === recipientType.INPERSONSIGNER && index > 0) && action.payload[index - 1].type !== recipientType.INPERSONSIGNER) {
// return state;
// }
// }
// state.recipients = action.payload;
// },
// setSigningOrder: (state, action: PayloadAction<boolean>) => {
// for (const recipient of state.recipients) {
// if (recipient.type === recipientType.INPERSONSIGNER) {
// if (state.signingOrder) return state;
// state.signingOrder = true;
// return state
// }
// }
// state.signingOrder = action.payload;
// },
// // Remove Recipients
// removeSelectedRecipient: (state, action: PayloadAction<Recipient>) => {
// console.log("removeSelectedRecipient Called")
// state.recipients = state.recipients.filter((recipient) => recipient.email !== action.payload.email);
// },
// // Add Color in Recipient
// addColorsToRecipient: (state) => {
// // const colors = generateUniqueColors(state.recipients.length);
// for (const [index, recipient] of state.recipients.entries()) {
// console.log(state)
// recipient.color = colors[index]
// }
// return state;
// },
// updateRecipientOrder: (state, action: PayloadAction<{ id: string; routingOrder: number }>) => {
// console.log("recipient order called Line 159")
// const { id, routingOrder } = action.payload;
// const recipient = state.recipients.find((r) => r.id === id || r.email === id);
// if (recipient) {
// recipient.routingOrder = routingOrder;
// }
// },
// updateRecipientIds: (state, action: PayloadAction<Recipient[]>) => {
// console.log("updateRecipientIds", console.table(action.payload));
// for (const recObj of state.recipients) {
// const email = recObj.email
// for (const recObj2 of action.payload) {
// recObj.id = recObj2.id;
// }
// }
// },
// resetSelRecipient: (state) => {
// state = initialState;
// return state;
// }
// },
// extraReducers: (builder) => {
// builder
// // Fetch Recipient - START
// .addCase(fetchRecipients.pending, (state) => {
// })
// .addCase(fetchRecipients.fulfilled, (state, action: PayloadAction<Recipient[]>) => {
// // console.log("Fetched recipients successfully:", action.payload);
// // Assign colors to recipients
// const assignedRecipients = action.payload.map((recipient, index) => ({
// ...recipient,
// color: colors[index], // Cycle if more recipients than colors
// }));
// state.recipients = assignedRecipients;
// })
// .addCase(fetchRecipients.rejected, (state, action) => {
// console.error("Failed to fetch recipients:", action.payload);
// toast.error("Failed to fetch recipients", {
// position: "bottom-right",
// autoClose: 5000,
// hideProgressBar: false,
// closeOnClick: false,
// pauseOnHover: true,
// draggable: true,
// progress: undefined,
// theme: "light",
// });
// })
// // Fetch Recipient - END
// // Add Recipient - START
// .addCase(addRecipientAsync.pending, (state) => {
// })
// .addCase(addRecipientAsync.fulfilled, (state, action: PayloadAction<Recipient[]>) => {
// // Optionally avoid duplicates if needed
// console.log("addRecipientAsync Called Line 258", action.payload);
// // const newRecipients = action.payload.filter(newRec => {
// // return !state.recipients.some(existing => existing existing.id === newRec.id);
// // });
// // const newRecipients = action.payload.filter(newRec => {
// // return !state.recipients.some(existing => "id" in existing && existing.id === newRec.id);
// // });
// // // Add new recipients and assign colors
// // const startIndex = state.recipients.length;
// // newRecipients.forEach((rec, index) => {
// // rec.color = colors[startIndex + index];
// // state.recipients.push(rec);
// // });
// state.recipients = action.payload.map((recipient, index) => ({
// ...recipient,
// color: colors[index % colors.length], // Cycle through colors
// }));
// })
// .addCase(addRecipientAsync.rejected, (state, action) => {
// console.error("Failed to fetch recipients:", action.payload);
// toast.error("Failed to fetch recipients", {
// position: "bottom-right",
// autoClose: 5000,
// hideProgressBar: false,
// closeOnClick: false,
// pauseOnHover: true,
// draggable: true,
// progress: undefined,
// theme: "light",
// });
// })
// // Add Recipient - END
// // Fetch Recipient - START
// .addCase(removeRecipientAsync.pending, (state) => {
// })
// .addCase(removeRecipientAsync.fulfilled, (state, action: PayloadAction<string | number>) => {
// state.recipients = state.recipients.filter(
// (recipient) => recipient.id !== action.payload && recipient.email !== action.payload
// );
// })
// .addCase(removeRecipientAsync.rejected, (state, action) => {
// console.error("Failed to Delete recipients:", action.payload);
// toast.error("Failed to Delete recipients", {
// position: "bottom-right",
// autoClose: 5000,
// hideProgressBar: false,
// closeOnClick: false,
// pauseOnHover: true,
// draggable: true,
// progress: undefined,
// theme: "light",
// });
// })
// // Fetch Recipient - END
// }
// });
// export const { addRecipient, setSelectedRecipients, toggleToTemplates, removeSelectedRecipient, setSigningOrder, addColorsToRecipient, updateRecipientIds, resetSelRecipient, updateRecipientOrder, resetRecipients } = selectedRecipientsSlice.actions;
// export default selectedRecipientsSlice.reducer;
import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import { toast } from 'react-toastify';
import colors from '../../utlity/colorsArr';
@ -342,7 +10,7 @@ export enum recipientType {
}
export interface Recipient {
id?: string;
id?: string | null;
firstName: string;
lastName: string;
routingOrder: number;
@ -356,7 +24,7 @@ export interface Recipient {
roleName: string
provideOwnTags?: boolean;
uuid?: string;
newOne: boolean;
newOne?: boolean;
}
export interface SelectedRecipientInt {
@ -467,7 +135,7 @@ export const fetchRecipients = createAsyncThunk<
// data = data.filter((recipient, indx) => {
// return recipient.type !== "CC";
// })
if (data.length === 0 && window.location.pathname.includes('/process-step-two')) {
window.location.href = window.location.href.replace("process-step-two", "process-step-one") // ✅ navigate using window
}
@ -484,21 +152,6 @@ const selectedRecipientsSlice = createSlice({
initialState,
reducers: {
addRecipient: (state, action: PayloadAction<Recipient>) => {
// Checking if meail already exist - START
// for (const recipient of state.recipients) {
// if (recipient.email === action.payload.email) {
// toast.dismiss();
// toast.error("Email already exists !", {
// position: "bottom-right",
// autoClose: 5000,
// theme: "light",
// });
// return state;
// }
// }
// Checking if meail already exist - END
if (action.payload.type === recipientType.INPERSONSIGNER) {
state.signingOrder = true;
state.recipients = [action.payload, ...state.recipients];

View File

@ -100,7 +100,6 @@ export interface TagsProperties {
"isCurrency"?: boolean;
}
export enum TagsTypes {
TEXT = "text",
SIGNATURE = "signature",
@ -119,15 +118,11 @@ export enum TagsTypes {
COMPANY = "company",
}
export enum SignTypeEnum {
selfSign = "self_sign",
multipleSign = "multi_sign"
}
export interface StylesInterface {
font: string,
italic: boolean,
@ -151,6 +146,7 @@ export interface DroppedItem {
id?: string;
icon: JSX.Element;
label?: string;
tooltip?: string;
type: string;
// TagsProperties - Other Properties depend on tag type - START