jai #21

Merged
jaipandey merged 7 commits from jai into main 2025-08-28 11:55:32 +00:00
76 changed files with 2462 additions and 2812 deletions
Showing only changes of commit 0a9c28925f - Show all commits

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

@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<title>Sign Made Easy</title>
</head>
<body>
<div id="root"></div>

View File

@ -58,15 +58,11 @@ const getInitials = (name: string) => {
const SigningOrderDiagram : React.FC<Signer[]> = (signers) => {
console.log(signers, "Line 59")
const grouped = groupByRoutingOrder(signers.signers);
const sortedOrders = Object.keys(grouped)
.map(Number)
.sort((a, b) => a - b);
console.log("sortedOrders",sortedOrders,grouped)
const currentProcessingOrder =
sortedOrders.find((order) =>
grouped[order].some((signer) => !signer.completed)

View File

@ -1,12 +1,14 @@
import React, { useEffect, useRef, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { FaSignOutAlt, FaUser, FaBuilding, FaChevronDown, FaCheck } from "react-icons/fa";
import { FaSignOutAlt, FaUser, FaBuilding, FaChevronDown, FaCheck, FaBars } from "react-icons/fa";
import api from '../config/api';
interface AccountNavProps {
accountName?: string | null;
transactionName?: string | null;
showSideBar?: boolean;
setShowSideBar?: (show: boolean) => void;
isMobile?: boolean;
}
interface Account {
@ -40,10 +42,13 @@ const dispatchSessionStorageChange = (key: string, newValue: any) => {
}));
};
const CommonNav: React.FC<AccountNavProps> = () => {
const CommonNav: React.FC<AccountNavProps> = ({
showSideBar,
setShowSideBar,
isMobile = false
}) => {
const activeAccountId = JSON.parse(sessionStorage.getItem('activeAccountId') || 'null');
const userDetails = JSON.parse(sessionStorage.getItem('userDetails') || '{}');
console.log("activeAccountId", activeAccountId);
const [open, setOpen] = useState(false);
const [accountsOpen, setAccountsOpen] = useState(false);
@ -64,12 +69,10 @@ const CommonNav: React.FC<AccountNavProps> = () => {
},
});
console.log("user", user)
const getAccountDetails = async () => {
try {
let res = await api.get('/api/user/accounts');
let items = res?.data;
console.log('items', items);
const cleanedData: AccountDataArray[] = items.map((item: any) => ({
userId: item.userId,
@ -103,7 +106,6 @@ const CommonNav: React.FC<AccountNavProps> = () => {
};
const handleAccountSwitch = (account: any) => {
console.log("handleAccountSwitch", account);
// Update sessionStorage
sessionStorage.setItem('activeAccountId', JSON.stringify(account.accountId));
@ -112,7 +114,6 @@ const CommonNav: React.FC<AccountNavProps> = () => {
dispatchSessionStorageChange('activeAccountId', account.accountId);
// Update user state
setUser({
id: account.userId,
name: account.name,
@ -141,13 +142,12 @@ const CommonNav: React.FC<AccountNavProps> = () => {
setOpen(false);
};
const navigate = useNavigate();
const getUserDetails = async () => {
try {
let res = await api.get(`/api/user/details`);
console.log("getuser", res);
const item = res?.data;
if (item) {
const userData = {
@ -162,8 +162,6 @@ const CommonNav: React.FC<AccountNavProps> = () => {
},
};
console.log("userData", userData)
setUser(userData);
sessionStorage.setItem('userDetails', JSON.stringify(userData));
sessionStorage.setItem('activeAccountId', JSON.stringify(userData.account.id));
@ -171,10 +169,7 @@ const CommonNav: React.FC<AccountNavProps> = () => {
// Dispatch event for initial load
dispatchSessionStorageChange('activeAccountId', userData.account.id);
console.log("Data is saved in sessionStorage");
}
} catch (error) {
console.error("Error fetching user details:", error);
}
@ -194,17 +189,7 @@ const CommonNav: React.FC<AccountNavProps> = () => {
.split("/")
.filter((x) => x && isNaN(Number(x)));
// Special case: if first segment is 's' and next is 'settings', remove 's'
const pathnames =
rawPathnames[0] === "s" && rawPathnames[1] === "settings"
? rawPathnames.slice(1)
: rawPathnames;
const labelMap: Record<string, string> = {
accounts: "Accounts",
transactions: "Transactions",
templates: "Templates"
};
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
@ -244,11 +229,39 @@ const CommonNav: React.FC<AccountNavProps> = () => {
}
};
const handleSidebarToggle = () => {
if (setShowSideBar) {
setShowSideBar(!showSideBar);
}
};
// Special case: if first segment is 's' and next is 'settings', remove 's'
const pathnames =
rawPathnames[0] === "s" && rawPathnames[1] === "settings"
? rawPathnames.slice(1)
: rawPathnames;
const labelMap: Record<string, string> = {
accounts: "Accounts",
transactions: "Transactions",
templates: "Templates",
};
const formatSegment = (segment: string) =>
segment
.replace(/[-_]/g, " ")
.replace(/\b\w/g, (char) => char.toUpperCase());
// If URL has accounts → transactions, only keep "transactions"
let filteredPathnames = [...pathnames];
const accIndex = pathnames.indexOf("accounts");
const txnIndex = pathnames.indexOf("transactions");
if (accIndex !== -1 && txnIndex !== -1 && txnIndex > accIndex) {
// keep only "transactions" and everything after it
filteredPathnames = pathnames.slice(txnIndex);
}
const ShimmerRow = () => (
<div className="animate-pulse px-4 py-3 border-b border-gray-100 last:border-b-0">
<div className="flex items-center space-x-3">
@ -263,34 +276,51 @@ const CommonNav: React.FC<AccountNavProps> = () => {
);
return (
<header className="w-full px-6 py-1.5 flex justify-between items-center bg-white border-b border-gray-200">
<nav className="text-md font-medium text-gray-800 capitalize flex items-center flex-wrap">
{pathnames.length === 0 ? (
<span className="text-gray-900 font-semibold">Home</span>
) : (
pathnames.map((segment, index) => {
const label = labelMap[segment] || formatSegment(segment);
const to = "/" + pathnames.slice(0, index + 1).join("/");
const isLast = index === pathnames.length - 1;
return (
<span key={to} className="flex items-center">
{index > 0 && <span className="mx-2 text-gray-400">{">"}</span>}
{!isLast ? (
<Link
to={to}
className="text-blue-600 hover:text-blue-700 hover:underline transition-colors"
>
{label}
</Link>
) : (
<span className="text-gray-900 font-semibold">{label}</span>
)}
</span>
);
})
<header className="w-full px-3 py-1.5 flex justify-between items-center bg-white border-b border-gray-200">
<div className="flex items-center space-x-4">
{/* Mobile Hamburger Menu - Only show on mobile */}
{isMobile && (
<div className='flex items-center justify-start'>
<span className='text-[var(--primary)] text-xl text-center tracking-widest font-medium text-shadow-2xs'>SME</span>
<button
onClick={handleSidebarToggle}
className="p-2 rounded-lg hover:bg-gray-100 transition-colors duration-200 text-gray-600 hover:text-gray-900"
aria-label="Toggle sidebar"
>
<FaBars className="text-lg" />
</button>
</div>
)}
</nav>
{/* Breadcrumb Navigation */}
<nav className="text-md font-medium text-gray-800 capitalize flex items-center flex-wrap">
{filteredPathnames.length === 0 ? (
<span className="text-gray-900 font-semibold">Home</span>
) : (
filteredPathnames.map((segment, index) => {
const label = labelMap[segment] || formatSegment(segment);
const to = "/" + filteredPathnames.slice(0, index + 1).join("/");
const isLast = index === filteredPathnames.length - 1;
return (
<span key={to} className="flex items-center">
{index > 0 && <span className="mx-2 text-gray-400">{">"}</span>}
{!isLast ? (
<Link
to={to}
className="text-blue-600 hover:text-blue-700 hover:underline transition-colors"
>
{label}
</Link>
) : (
<span className="text-gray-900 font-semibold">{label}</span>
)}
</span>
);
})
)}
</nav>
</div>
<div className="flex items-center space-x-2">
<div className="relative" ref={dropdownRef}>
@ -407,6 +437,20 @@ const CommonNav: React.FC<AccountNavProps> = () => {
</div>
</header>
);
};
// const ShimmerRow = () => (
// <div className="animate-pulse px-4 py-3 border-b border-gray-100 last:border-b-0">
// <div className="flex items-center space-x-3">
// <div className="w-8 h-8 bg-gray-200 rounded-full"></div>
// <div className="flex-1 space-y-2">
// <div className="h-4 bg-gray-200 rounded w-3/4"></div>
// <div className="h-3 bg-gray-200 rounded w-1/2"></div>
// </div>
// <div className="w-16 h-6 bg-gray-200 rounded"></div>
// </div>
// </div>
// );
// };
}
export default CommonNav;

View File

@ -108,7 +108,6 @@ const Account = () => {
JSON.parse(sessionStorage.getItem('activeAccountId') || 'null')
);
console.log("activeAccountId Trans.", activeAccountId)
// const { accountId } = useParams<{ accountId: string }>();
const [transactions, setTransactions] = useState<Transaction[]>([]);
const [accountsData, setAccountsData] = useState([])
@ -249,7 +248,7 @@ const Account = () => {
<Cards type="transactions" onOpenModal={handleOpenModal} cards={cards}
isLoading={isLoading} />
<section className="my-4 mx-3">
<TransactionDataTable />
<TransactionDataTable activeAccountId={activeAccountId}/>
</section>
{isModalOpen && <AddInviteModal onClose={() => setIsModalOpen(false)} onInvite={handleInvite} inviteLoading={inviteLoading}

View File

@ -42,7 +42,6 @@ const dispatchSessionStorageChange = (key: string, newValue: any) => {
const AccountNav: React.FC<AccountNavProps> = ({ accountName = null, transactionName = null }) => {
const activeAccountId = JSON.parse(sessionStorage.getItem('activeAccountId') || 'null');
const userDetails = JSON.parse(sessionStorage.getItem('userDetails') || '{}');
console.log("activeAccountId", activeAccountId);
const [open, setOpen] = useState(false);
const [accountsOpen, setAccountsOpen] = useState(false);
@ -63,12 +62,10 @@ const AccountNav: React.FC<AccountNavProps> = ({ accountName = null, transaction
},
});
console.log("user", user)
const getAccountDetails = async () => {
try {
let res = await api.get('/api/user/accounts');
let items = res?.data;
console.log('items', items);
const cleanedData: AccountDataArray[] = items.map((item: any) => ({
userId: item.userId,
@ -102,7 +99,6 @@ const AccountNav: React.FC<AccountNavProps> = ({ accountName = null, transaction
};
const handleAccountSwitch = (account: any) => {
console.log("handleAccountSwitch", account);
// Update sessionStorage
sessionStorage.setItem('activeAccountId', JSON.stringify(account.accountId));
@ -146,7 +142,7 @@ const AccountNav: React.FC<AccountNavProps> = ({ accountName = null, transaction
const getUserDetails = async () => {
try {
let res = await api.get(`/api/user/details`);
console.log("getuser", res);
const item = res?.data;
if (item) {
const userData = {
@ -161,16 +157,12 @@ const AccountNav: React.FC<AccountNavProps> = ({ accountName = null, transaction
},
};
console.log("userData",userData)
setUser(userData);
sessionStorage.setItem('userDetails', JSON.stringify(userData));
sessionStorage.setItem('activeAccountId', JSON.stringify(userData.account.id));
// Dispatch event for initial load
dispatchSessionStorageChange('activeAccountId', userData.account.id);
console.log("Data is saved in sessionStorage");
}

View File

@ -99,7 +99,6 @@ const Accounts = () => {
const handleAction = async (accountId: string, action: 'accept' | 'reject') => {
try {
let response = await api.post(`/api/accounts/${accountId}/accept/invite`)
console.log(response)
if (response.data.status === 202) {
toast.success("Login Successful", {
position: "top-center",

View File

@ -22,16 +22,12 @@ const statusColorMap = {
};
const TransactionDataTable = () => {
const TransactionDataTable = ({activeAccountId}) => {
const navigate = useNavigate()
const loaction = useLocation()
console.log("loaction", loaction.pathname);
const [currentEmailId, setCurrentEmailId] = useState<string | null>('null');
const [selectedTransactions, setSelectedTransactions] = useState<number[]>([]);
const [activeAccountId, setActiveAccountId] = useState<string | null>(
JSON.parse(sessionStorage.getItem('activeAccountId') || 'null')
);
const [loading, setLoading] = useState(false)
const fetchTransactions = async () => {

View File

@ -6,7 +6,6 @@ import { Link, useNavigate } from "react-router-dom";
import OAuthGoogle from "./OAuthGoogle";
import { Bounce, toast } from "react-toastify";
// import Cookies from "js-cookie";
import { updateUser } from "../../store/slices/userSlice";
import { useDispatch } from "react-redux";
import { AppDispatch } from "../../store/store";
// import api from "../../config/api";
@ -27,18 +26,15 @@ function LoginForm() {
const handleNextClick = () => {
console.log('Next Button Clicked');
// Validation Starts
if (formData.email === "") {
console.log('All Fields are Required');
return;
}
// Validate Email Format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(formData.email)) {
console.log("Invalid email format");
return;
}
// Validation Ends
@ -47,18 +43,14 @@ function LoginForm() {
axios.get(`${import.meta.env.VITE_BASE_URI}/api/auth/user?email=${formData.email}`, { headers: { "ngrok-skip-browser-warning": "69420" } })
.then((res) => {
console.log(res, "Cache Key res", formData.email)
console.log(res.data, "Cache Key res 2", formData.email)
if (res.status === 200) {
toast.dismiss();
console.log('User Exists');
setCacheKey(res.data);
setNextClick(true);
}
})
.catch((err) => {
console.log('User Does Not Exists');
toast.dismiss();
toast.error("User Does Not Exists", {
position: "top-center",
@ -76,25 +68,20 @@ function LoginForm() {
}
const handleFormLoginClick = () => {
console.log('Login Function Called Line 7 LoginForm.tsx');
// Validation Starts
if (formData.email === "" || formData.password === "") {
console.log('All Fields are Required');
return;
}
// Validate Email Format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(formData.email)) {
console.log("Invalid email format");
return;
}
// Validation Ends
// Login API Call
console.log('Login API Call');
console.log(formData, "Submitting Data :", { cacheKey: cacheKey, password: formData.password });
axios.post(`${import.meta.env.VITE_BASE_URI}/api/auth/login`,
{ cacheKey: cacheKey, password: formData.password },
{
@ -106,10 +93,9 @@ function LoginForm() {
}
)
.then((res) => {
console.log(res.status, "Response Status Line 42 LoginForm.tsx", res);
if (res.status === 200) {
toast.dismiss();
// console.log('User Logined Successfully Line 45 LoginForm.tsx headerCookie:', res.headers.authorization);
// Cookies.set("authorization", res.headers.authorization, {
// path: "/",
// secure: true, // Required for HTTPS
@ -132,9 +118,7 @@ function LoginForm() {
}
})
.catch((err) => {
console.log(err, "ERROR")
if (err.status === 401) {
console.log('Unauthorized');
toast.dismiss();
toast.error("Credentials Not Match", {
position: "top-center",
@ -148,7 +132,6 @@ function LoginForm() {
transition: Bounce,
});
} else {
console.log('Some Error Occurred');
toast.dismiss();
toast.error("Some Error Occurred", {
position: "top-center",
@ -206,7 +189,7 @@ function LoginForm() {
<p>or login with social platforms</p>
<div className="social-icons">
<OAuthGoogle />
<OAuthGoogle isLogin={true} />
</div>
<div>

View File

@ -19,16 +19,14 @@ interface OAuthGoogleProps {
isLogin: boolean
}
const OAuthGoogle: React.FC<OAuthGoogleProps> = ({isLogin}) => {
const OAuthGoogle: React.FC<OAuthGoogleProps> = ({ isLogin }) => {
const dispatch = useDispatch<AppDispatch>();
const navigate = useNavigate();
// Define the success handler type (based on the Google login response)
const responseMessage = (response: GoogleResponse) => {
console.log(response, "OAuthGoogle .tsx Line 23 Response from Google");
const token = response.credential;
console.log(token, 'token');
axios.get(`${import.meta.env.VITE_BASE_URI}/api/oauth2/authorization/google?token=${token}`, {
headers: {
@ -38,7 +36,6 @@ const OAuthGoogle: React.FC<OAuthGoogleProps> = ({isLogin}) => {
.then((res) => {
if (res.status === 200 || res.status === 201) {
toast.dismiss();
console.log('User Logined Successfully Line 45 LoginForm.tsx headerCookie:', res.headers.authorization);
dispatch(updateUser({ ...res.data, authorized: true, accessToken: res.headers.authorization }));
@ -52,8 +49,6 @@ const OAuthGoogle: React.FC<OAuthGoogleProps> = ({isLogin}) => {
const decoded = jwtDecode(token);
console.log(decoded, 'decoded');
};
// Define the error handler type (error can be of any type)

View File

@ -22,14 +22,12 @@ interface FormDataState {
function RegisterForm() {
console.log("RegisterForm Component Rendered");
const [formData, setForm] = useState<FormDataState>({ email: "", password: "", confirmPassword: "", firstName: "", lastName: "" });
const dispatch = useDispatch<AppDispatch>();
const navigate = useNavigate();
const handleFormRegisterClick = () => {
console.log('Register Function Called Line 7 RegisterForm.tsx');
formData.firstName = formData.firstName.trim();
formData.lastName = formData.lastName.trim();
// Validation Starts
@ -48,7 +46,6 @@ function RegisterForm() {
// Register API Call
console.log('Register API Call');
console.dir(formData);
axios.post(`${import.meta.env.VITE_BASE_URI}/api/auth/signup`, { firstName: formData.firstName, lastName: formData.lastName, email: formData.email, password: formData.password }, {
@ -59,10 +56,8 @@ function RegisterForm() {
}
})
.then((res) => {
console.log(res.status, "Response Status Line 42 RegisterForm.tsx");
if (res.status === 201) {
console.log(res, "line 58");
toast.dismiss();
// dispatch(updateUser({ ...res.data, authorized: true, accessToken: res.headers.authorization }));
// dispatch(updateUser({ ...res.data, authorized: true }));
@ -71,7 +66,6 @@ function RegisterForm() {
})
.catch((err) => {
if (err.status === 409) {
console.log('User Already Exists');
toast.dismiss();
toast.error("User Already Exists", {
position: "top-center",
@ -85,7 +79,6 @@ function RegisterForm() {
transition: Bounce,
});
} else {
console.log('Some Error Occurred');
toast.dismiss();
toast.error("Some Error Occurred", {
position: "top-center",

View File

@ -1,32 +1,40 @@
import React from 'react'
import { MdKeyboardArrowDown } from 'react-icons/md';
import React, { useState } from 'react'
import { MdKeyboardArrowDown, MdOutlineNavigateNext } from 'react-icons/md';
import { DocumentType } from './SignDocument';
import { GrFormPrevious } from 'react-icons/gr';
interface DocumentPagesInterface {
selectedDocuments: DocumentType[];
selectedDocuments: DocumentType[] | null;
setDropDownTogglePage: React.Dispatch<React.SetStateAction<string>>;
dropDownTogglePage: string;
}
const DocumentPages = ({ selectedDocuments, setDropDownTogglePage, dropDownTogglePage }: DocumentPagesInterface) => {
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) => {
return (
return (
<div
key={indx}
// tabIndex={1}
// onBlur={() => setDropDownTogglePage('')}
>
<div
onClick={() => (`${(dropDownTogglePage === 'pageDropDown' + indx) ? '' : 'pageDropDown' + indx}`)}
onClick={() => {
setDropDownTogglePage(`${(dropDownTogglePage === 'pageDropDown' + indx) ? '' : 'pageDropDown' + indx}`)
}
}
className={`p-2 ${(dropDownTogglePage === 'pageDropDown' + indx) ? "bg-[var(--primary)]" : "bg-slate-200"} flex flex-col justify-center items-center gap-2 rounded`}>
{
document.pages != undefined && <img
key={indx}
className='rounded-sm shadow'
src={document.pages[0].src}
src={"data:image/png;base64," + document.thumbnail}
alt="" />
}
@ -40,15 +48,53 @@ const DocumentPages = ({ selectedDocuments, setDropDownTogglePage, dropDownToggl
{
dropDownTogglePage === 'pageDropDown' + indx &&
<div className='my-1 flex justify-center items-center gap-1 flex-wrap'>
{document.pages != undefined && document.pages.map((img, indx) => (
<a
href={"#" + document.documentId + indx}
className='max-w-max px-4 py-2 shadow cursor-pointer border-1 rounded-sm border-slate-200 hover:border-[var(--primary)] transition-all duration-300 bg-slate-300'
>
<p className='text-center text-xs text-slate-600'>{indx + 1}</p>
</a>
))}
<div className="my-1 flex justify-center items-center gap-2 flex-wrap">
{/* Prev Button */}
<a
href={"#" + document.documentId + (currentPage - 1)}
className={`cursor-pointer px-2 py-1 shadow rounded-sm text-sm bg-slate-200 hover:border-[var(--primary)] transition-all duration-300 ${currentPage === 0 ? "pointer-events-none opacity-50" : ""
}`}
onClick={(e) => {
if (currentPage === 0) e.preventDefault();
else setCurrentPage(currentPage - 1);
}}
>
<GrFormPrevious />
</a>
{/* Page Selector */}
<select
className="w-[58px] py-1 text-xs text-slate-400 outline-none"
value={currentPage}
onChange={(e) => {
const newPage = Number(e.target.value);
setCurrentPage(newPage);
window.location.hash = document.documentId + "" + newPage;
}}
>
{document.pages != undefined && document.pages.map((_, pageIndex) => (
<option key={pageIndex} value={pageIndex}>
{pageIndex + 1}
</option>
))}
</select>
<span className="text-xs text-slate-600">
/ {document.pages?.length}
</span>
{/* Next Button */}
<a
href={"#" + document.documentId + (currentPage + 1)}
className={`cursor-pointer px-2 py-1 shadow rounded-sm text-sm bg-slate-200 hover:border-[var(--primary)] transition-all duration-300 ${currentPage === document.pages?.length - 1 ? "pointer-events-none opacity-50" : ""
}`}
onClick={(e) => {
if (currentPage === document.pages?.length - 1) e.preventDefault();
else setCurrentPage(currentPage + 1);
}}
>
<MdOutlineNavigateNext />
</a>
</div>
}

File diff suppressed because it is too large Load Diff

View File

@ -25,7 +25,6 @@ const Contacts = () => {
const [showModal, setShowModal] = useState(false)
const [editJsonData, setEditJsonData] = useState({})
const [actionStatus, setActionStatus] = useState("")
console.log("editJsonData", editJsonData)
const fetchContacts = async () => {
setLoading(true)
@ -46,7 +45,6 @@ const Contacts = () => {
}, [activeAccountId]);
const handleEdit = (contactId) => {
console.log('Edit contact:', contactId);
let jsonEditData = contacts.find((prev) => prev.id === contactId)
setEditJsonData(jsonEditData)
setActionStatus("Edit")
@ -55,7 +53,6 @@ const Contacts = () => {
};
const handleDelete = async (contactId) => {
console.log('Delete contact:', contactId);
try {
let res = await api.delete(`/api/accounts/${activeAccountId}/contacts/${contactId}`)

View File

@ -55,7 +55,6 @@ const ContactFormModal = ({
}, [actionStatus, editJsonData]);
const handleChange = (field: keyof ContactData, value: string) => {
console.log(field, value);
setFormData((prev) => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors((prev) => ({ ...prev, [field]: "" }));
@ -136,7 +135,6 @@ const ContactFormModal = ({
const validationErrors = validate();
let type = "Add";
let payload = formData;
console.log(payload);
if (Object.keys(validationErrors).length > 0) {
setErrors(validationErrors);
@ -170,113 +168,71 @@ const ContactFormModal = ({
return (
<div className="fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm bg-opacity-50 bg-black/30">
<div className="bg-white rounded-md p-6 max-w-[700px] w-full shadow-lg relative">
<div className="ms-2 space-y-2 max-w-[60vw]">
<h2 className="text-lg font-medium text-slate-500">{`${actionStatus} Contact`}</h2>
<div className="fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm bg-black/30 bg-opacity-50 p-4 sm:p-6">
<div className="bg-white rounded-md p-6 max-w-[700px] w-full sm:max-w-[700px] shadow-lg relative overflow-auto max-h-[90vh]">
<div className="space-y-4">
<h2 className="text-lg font-medium text-slate-500">{`${actionStatus} Contact`}</h2>
<div className="grid grid-cols-2 gap-3">
{[
{ label: "First Name", field: "firstName" },
{ label: "Last Name", field: "lastName" },
{ label: "Email", field: "email", fieldType: "email" },
{ label: "Title", field: "title" },
{ label: "Company", field: "company" },
{ label: "Website", field: "website", fieldType: "url" },
{ label: "Phone", field: "phone", fieldType: "tel" },
].map(({ label, field, fieldType }) => (
<div key={field} className="flex flex-col">
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">
{label}
</label>
<input
type={fieldType ? fieldType : "text"}
value={(formData[field as keyof ContactData] as string) || ""}
onChange={(e) =>
handleChange(field as keyof ContactData, e.target.value)
}
required={true}
className="px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
placeholder={`Enter ${label}`}
/>
{errors[field] && (
<span className="text-sm text-red-500 mt-1">
{errors[field]}
</span>
)}
</div>
))}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{[
{ label: "First Name", field: "firstName" },
{ label: "Last Name", field: "lastName" },
{ label: "Email", field: "email", fieldType: "email" },
{ label: "Title", field: "title" },
{ label: "Company", field: "company" },
{ label: "Website", field: "website", fieldType: "url" },
{ label: "Phone", field: "phone", fieldType: "tel" },
].map(({ label, field, fieldType }) => (
<div key={field} className="flex flex-col">
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">
{label}
</label>
<input
type={fieldType ?? "text"}
value={(formData[field as keyof ContactData] as string) || ""}
onChange={(e) =>
handleChange(field as keyof ContactData, e.target.value)
}
required
className="px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
placeholder={`Enter ${label}`}
/>
{errors[field] && (
<span className="text-sm text-red-500 mt-1">{errors[field]}</span>
)}
</div>
))}
</div>
{/* <div>
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">Phone Number</label>
<div className="space-y-2">
{formData?.phones?.map((phone, index) => (
<div key={index} className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<input
type="text"
value={phone}
onChange={(e) => handlePhoneChange(index, e.target.value)}
className="flex-1 px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
maxLength={15}
placeholder='Enter Phone Numbers'
/>
{formData.phones.length > 1 && (
<button
type="button"
onClick={() => removePhoneField(index)}
className="text-xs text-red-500 hover:underline"
>
Remove
</button>
)}
</div>
{errors[`phones_${index}`] && (
<span className="text-sm text-red-500">{errors[`phones_${index}`]}</span>
)}
</div>
))}
<button
type="button"
onClick={addPhoneField}
className="text-sm text-blue-500 hover:underline mt-1 cursor-pointer"
>
+ Add another phone
</button>
</div>
</div> */}
<div className="flex justify-end">
<button
type="button"
onClick={() => setShowModal((prev) => !prev)}
disabled={loading}
className="bg-gray-300 px-5 py-1.5 rounded-md text-slate-700 text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer me-3"
>
{" "}
Cancel
</button>
<button
type="button"
onClick={handleSubmit}
disabled={loading}
className="bg-gradient-to-br from-[var(--primary)] to-blue-600 px-5 py-1.5 rounded-md text-white text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
>
{loading ? (
<>
<FaSpinner className="animate-spin inline-block mr-2" />
SAVING...
</>
) : (
`${actionStatus?.toUpperCase() || "SAVE"} CONTACT`
)}
</button>
</div>
</div>
<div className="flex flex-col sm:flex-row justify-end gap-3 mt-4">
<button
type="button"
onClick={() => setShowModal((prev) => !prev)}
disabled={loading}
className="bg-gray-300 px-5 py-1.5 rounded-md text-slate-700 text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
>
Cancel
</button>
<button
type="button"
onClick={handleSubmit}
disabled={loading}
className="bg-gradient-to-br from-[var(--primary)] to-blue-600 px-5 py-1.5 rounded-md text-white text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
>
{loading ? (
<>
<FaSpinner className="animate-spin inline-block mr-2" />
SAVING...
</>
) : (
`${actionStatus?.toUpperCase() || "SAVE"} CONTACT`
)}
</button>
</div>
</div>
</div>
</div>
);
};

View File

@ -1,3 +1,4 @@
// Dashboard.jsx - Updated version
import React, { useEffect, useLayoutEffect } from 'react'
import SideBar from './SideBar'
import { Outlet, useNavigate } from 'react-router-dom'
@ -22,6 +23,7 @@ import CommonNav from '../CommonNav'
function Dashboard() {
const [showSideBar, setShowSideBar] = React.useState(true)
const [showConfetti, setShowConfetti] = React.useState(false)
const [isMobile, setIsMobile] = React.useState(false)
const navigate = useNavigate();
const dispatch = useDispatch();
@ -45,7 +47,7 @@ function Dashboard() {
// Clear all if transaction success
if (transactionStatus === TRANSACTION_STATUS_ENUMS.TRANSACTION_SEND_SUCCESS || transactionStatus === TRANSACTION_STATUS_ENUMS.TRANSACTION_INITIATED || transactionStatus === TRANSACTION_STATUS_ENUMS.TRANSACTION_SEND_FAILURE) {
console.log("IN MIC CHECK");
dispatch(resetSelDoc())
dispatch(resetSelRecipient())
dispatch(clearTransaction())
@ -74,8 +76,6 @@ function Dashboard() {
}
}, [])
useEffect(() => {
if (transactionStatus === TRANSACTION_STATUS_ENUMS.TRANSACTION_SEND_SUCCESS || transactionStatus === TRANSACTION_STATUS_ENUMS.TRANSACTION_INITIATED) return;
@ -86,13 +86,11 @@ function Dashboard() {
if (documentSignType && transactionStatus === TRANSACTION_STATUS_ENUMS.TRANSACTION_NOT_INITIATED) {
if (documentSignType === 'self-sign') {
console.log('Self Sign');
setTimeout(() => {
navigate('/process-step-one');
}, 1000)
return
} else if (documentSignType === 'multiple-sign') {
console.log('multiple-sign');
setTimeout(() => {
navigate('/process-step-one');
}, 1000)
@ -102,35 +100,55 @@ function Dashboard() {
dispatch(hideLoader());
}, [documentSignType])
useEffect(() => {
if (showConfetti) {
const duration = 3000;
const end = Date.now() + duration;
useEffect(() => {
if (showConfetti) {
const duration = 3000;
const end = Date.now() + duration;
const interval = setInterval(() => {
if (Date.now() > end) {
clearInterval(interval);
return;
}
const interval = setInterval(() => {
if (Date.now() > end) {
clearInterval(interval);
return;
}
confetti({
particleCount: 80, // more particles
angle: Math.random() * 360, // fire in random direction
spread: 220, // wider spread
startVelocity: 15, // more power
scalar: 1.2, // bigger pieces (default is 1)
origin: {
x: Math.random(),
y: Math.random() * 0.6,
},
zIndex: 9999,
});
}, 350); // fire every 150ms
}
}, [showConfetti]);
confetti({
particleCount: 80, // more particles
angle: Math.random() * 360, // fire in random direction
spread: 220, // wider spread
startVelocity: 15, // more power
scalar: 1.2, // bigger pieces (default is 1)
origin: {
x: Math.random(),
y: Math.random() * 0.6,
},
zIndex: 9999,
});
}, 350); // fire every 150ms
useEffect(() => {
// Function to handle window resize
const handleResize = () => {
const mobile = window.innerWidth <= 768;
setIsMobile(mobile);
if (mobile) {
setShowSideBar(false); // hide sidebar on mobile by default
} else {
setShowSideBar(true); // show sidebar on desktop
}
}, [showConfetti]);
};
// Set sidebar visibility on mount
handleResize();
// Add event listener
window.addEventListener('resize', handleResize);
// Cleanup listener on unmount
return () => window.removeEventListener('resize', handleResize);
}, []);
return (
<>
@ -165,19 +183,44 @@ function Dashboard() {
{
user?.authorized &&
<div className={`relative`}>
{/* Complet DashBoard Back Side SideBar */}
{/* Mobile Overlay when sidebar is open */}
{isMobile && showSideBar && (
<div
className="fixed inset-0 bg-black/30 bg-opacity-50 z-40"
onClick={() => setShowSideBar(false)}
/>
)}
{/* Complete Dashboard Back Side SideBar */}
<div className={`relative w-full h-screen overflow-hidden bg-[var(--dashBoardBg)] ${(globalLoader.isLoading || globalModalIsOpen) ? 'pointer-events-none' : ''}`}>
<SideBar showSideBar={showSideBar} setShowSideBar={setShowSideBar} />
<SideBar
showSideBar={showSideBar}
setShowSideBar={setShowSideBar}
isMobile={isMobile}
/>
{/* On Top Main Content - START */}
<div className={`overflow-y-auto absolute no-scrollbar ${showSideBar ? 'w-[calc(100%-250px)]' : 'w-[calc(100%-60px)]'} h-full right-0 bottom-0 overflow-hidden bg-[var(--mainViewBg)] transition-all duration-300`}>
<div
className={`overflow-y-auto absolute no-scrollbar h-full right-0 bottom-0 overflow-hidden bg-[var(--mainViewBg)]`}
style={{
width: !isMobile
? (showSideBar ? 'calc(100% - 250px)' : 'calc(100% - 60px)')
: '100%', // Full width on mobile
transition: 'width 0.6s ease'
}}
>
{/* Main Content */}
<div className=''>
<CommonNav />
<div>
<CommonNav
showSideBar={showSideBar}
setShowSideBar={setShowSideBar}
isMobile={isMobile}
/>
<Outlet />
</div>
</div>
{/* On Top Main Content - END */}
</div>

View File

@ -25,7 +25,6 @@ const NavLink: React.FC<NavLinkProps> = ({ to, icon, label, showSideBar, menuPat
const location = useLocation();
const isActive = menuPathMap[location.pathname] === label;
console.log('Line 26' , to, icon, label, showSideBar, menuPathMap , "Check" , menuPathMap[location.pathname] === label)
// const [transactionFilter, setTransationFilter] = useState<TransactionFilterEnum>(TransactionFilterEnum.ALL)

View File

@ -77,52 +77,97 @@ const SendForSign: React.FC<Props> = ({ showSideBar }) => {
// }
return (
<div
id='send-for-sign-self-sign-btn'
className='relative max-h-max pb-3'
<div
id='send-for-sign-self-sign-btn'
className='relative max-h-max pb-3'
tabIndex={0}
ref={dropDownRef}
onBlur={() => setSendForSignDropdown(false)}
>
<div
{/* <div
className={`flex justify-between items-center gap-2 cursor-pointer bg-[var(--sidebarDropDownBg)] rounded text-[var(--sendForSignTextCol)] ${showSideBar ? "" : "pt-[0.4rem] pr-[0.6rem] pb-[0.4rem] pl-[0.2rem]"}`}>
<div
onClick={() => handleStartSectionClick(SignTypeEnum.multipleSign)}
className={`w-full`}>
<div
onClick={() => handleStartSectionClick(SignTypeEnum.multipleSign)}
className={`w-full`}>
{
showSideBar ?
<p
className='text-center text-sm'>Send for signature</p>
<p
className='text-center text-sm'>Send for signature</p>
:
<IoIosSend className={`pl-2 text-3xl`} />
}
</div>
{showSideBar &&
<p
className=' border-[var(--sendForSignTextCol)] px-2 py-2'>
className=' border-[var(--sendForSignTextCol)] pe-2 py-2'>
<IoMdArrowDropdown
onClick={() => setSendForSignDropdown(!sendForSignDropdown)}
className={`text-2xl ${sendForSignDropdown ? 'rotate-180' : ''} transition-all duration-150`} />
</p>}
</div> */}
<div
className={`flex items-center gap-0.5 cursor-pointer text-[var(--sendForSignTextCol)]`}
>
<div
onClick={() => handleStartSectionClick(SignTypeEnum.multipleSign)}
className={`
flex items-center justify-center
bg-[var(--sidebarDropDownBg)]
text-center
px-2 py-2.5
overflow-hidden
transition-all duration-300 ease-in-out w-full
${showSideBar ? "rounded-l" : "rounded"}
`}
style={{ whiteSpace: "nowrap" }}
>
{showSideBar ? (
<p className="text-sm select-none">Send for signature</p>
) : (
<IoIosSend className="text-2xl" />
)}
</div>
{showSideBar && (
<div
className="rounded-r btn px-2 py-2 bg-[var(--sidebarDropDownBg)] transition-all duration-300 ease-in-out flex items-center justify-center"
style={{ opacity: showSideBar ? 1 : 0 }}
>
<IoMdArrowDropdown
onClick={() => setSendForSignDropdown(!sendForSignDropdown)}
className={`text-2xl transition-transform duration-150 ${sendForSignDropdown ? "rotate-180" : ""
}`}
/>
</div>
)}
</div>
{/* Drop Down Box */}
{
sendForSignDropdown &&
<div className={`w-[300px] rounded absolute z-40 bg-[var(--sendForSignDropDownBg)] shadow-lg top-[54px] text-left outline-none`}>
<div className='py-3 px-8 leading-6 rounded-t-sm hover:bg-[var(--sendForSignDropDownHover)] cursor-pointer'
onClick={() => handleStartSectionClick(SignTypeEnum.selfSign)}>
<p>Self Sign</p>
<p className='text-[var(--greyTextCol)] text-sm'>You're the only signer.</p>
<div className={`w-[220px] sm:w-[260px] lg:w-[250px] rounded absolute z-40 bg-[var(--sendForSignDropDownBg)] shadow-lg top-[52px] text-left outline-none`}>
<div
className='py-2 px-6 leading-5 rounded-t-sm hover:bg-[var(--sendForSignDropDownHover)] cursor-pointer'
onClick={() => handleStartSectionClick(SignTypeEnum.selfSign)}
>
<p className='text-sm sm:text-base'>Self Sign</p>
<p className='text-[var(--greyTextCol)] text-xs sm:text-sm'>You're the only signer.</p>
</div>
<div className='w-full h-[1px] opacity-30 bg-[var(--greyTextCol)]'></div>
<div className='py-3 px-8 leading-6 rounded-b-sm hover:bg-[var(--sendForSignDropDownHover)] cursor-pointer'
onClick={() => handleStartSectionClick(SignTypeEnum.multipleSign)}>
<p>Send for Sign</p>
<p className='text-[var(--greyTextCol)] text-sm'>You and other need to sign.</p>
<div
className='py-2 px-6 leading-5 rounded-b-sm hover:bg-[var(--sendForSignDropDownHover)] cursor-pointer'
onClick={() => handleStartSectionClick(SignTypeEnum.multipleSign)}
>
<p className='text-sm sm:text-base'>Send for Sign</p>
<p className='text-[var(--greyTextCol)] text-xs sm:text-sm'>You and other need to sign.</p>
</div>
</div>
}
</div>
)
}

View File

@ -1,3 +1,4 @@
// SideBar.jsx - Updated version
import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import NavLink from './NavLink';
@ -16,6 +17,7 @@ import logoSME from '../../assets/SMELogo.png'
type SideBarProps = {
showSideBar: boolean;
setShowSideBar: React.Dispatch<React.SetStateAction<boolean>>;
isMobile?: boolean;
};
type MenuPathMap = {
@ -30,7 +32,7 @@ const menuPathMap: MenuPathMap = {
'/contacts': 'Contacts'
};
const SideBar: React.FC<SideBarProps> = ({ showSideBar, setShowSideBar }) => {
const SideBar: React.FC<SideBarProps> = ({ showSideBar, setShowSideBar, isMobile = false }) => {
const location = useLocation();
const [showLogoutModal, setShowLogoutModal] = useState(false);
@ -54,7 +56,17 @@ const SideBar: React.FC<SideBarProps> = ({ showSideBar, setShowSideBar }) => {
return (
<>
{/* Side Bar */}
<div className={`relative h-screen ${showSideBar ? 'w-[250px]' : 'w-[60px]'} transition-all duration-300 bg-[var(--sidebarBg)] shadow-md`}>
<div className={`
${isMobile ? 'fixed left-0 top-0 z-50' : 'relative'}
h-screen
${isMobile
? (showSideBar ? 'w-[250px] translate-x-0' : 'hidden -translate-x-full')
: (showSideBar ? 'w-[250px]' : 'w-[60px]')
}
transition-all duration-600
bg-[var(--sidebarBg)]
shadow-md
`}>
{/* Menu */}
<div className={`absolute top-0 ${showSideBar ? 'p-4' : 'py-4'} w-full max-h-max ${showSideBar ? '' : 'text-center'}`}>
<h1 className='w-full text-lg text-center tracking-widest font-medium text-gray-800'>
@ -76,10 +88,26 @@ const SideBar: React.FC<SideBarProps> = ({ showSideBar, setShowSideBar }) => {
{/* SideBar Toggle Button */}
<div
onClick={() => setShowSideBar(!showSideBar)}
className='absolute top-[100%] translate-y-[-100%] right-0 bg-[var(--dashBoardBg)] p-2 rounded-tl-sm rounded-bl-sm cursor-pointer transition-colors'
className={`
absolute top-[95%] translate-y-[-60%]
${isMobile
? (showSideBar ? 'right-2' : 'right-2')
: 'right-0 top-[100%] translate-y-[-100%]'
}
bg-[var(--dashBoardBg)] p-1
${isMobile
? 'rounded-md'
: (showSideBar ? 'rounded-tl-sm rounded-bl-sm' : 'rounded-tl-sm rounded-bl-sm')
}
cursor-pointer transition-colors
`}
>
<div className='absolute top-[-14px] right-0 w-[14px] h-[14px] rounded-full shadow-[5px_5px_0px_0px_rgba(255,255,255,1)]'></div>
<div className='absolute bottom-[-14px] right-0 w-[14px] h-[14px] rounded-full shadow-[5px_-5px_0px_0px_rgba(255,255,255,1)]'></div>
{!isMobile && (
<>
<div className='absolute top-[-14px] right-0 w-[14px] h-[14px] rounded-full shadow-[5px_5px_0px_0px_rgba(255,255,255,1)]'></div>
<div className='absolute bottom-[-14px] right-0 w-[14px] h-[14px] rounded-full shadow-[5px_-5px_0px_0px_rgba(255,255,255,1)]'></div>
</>
)}
{showSideBar ? (
<BsLayoutSidebarInsetReverse className='fill-[var(--primary)] hover:text-[var(--primary)] transition-all text-2xl' />
@ -113,7 +141,7 @@ const SideBar: React.FC<SideBarProps> = ({ showSideBar, setShowSideBar }) => {
{/* Logout Confirmation Modal */}
{showLogoutModal && (
<div className="fixed inset-0 backdrop-blur-sm flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl p-6 w-80">
<div className="bg-white rounded-lg shadow-xl p-4 sm:p-6 w-70 sm:w-40 lg:w-80">
<h3 className="text-lg font-medium text-gray-800 mb-4">Confirm Logout</h3>
<p className="text-gray-600 mb-6">Are you sure you want to log out?</p>
<div className="flex justify-end gap-3">

View File

@ -72,9 +72,6 @@ const Home = () => {
const userData = useSelector((state: RootState) => state.user);
console.log("activeAccountId", activeAccountId);
console.log("cards", cards);
const getDashboardData = async () => {
if (!activeAccountId) return;
@ -86,7 +83,7 @@ const Home = () => {
try {
const res = await api.get(`/api/accounts/${userData.account.id}/dashboard`, { params: payload });
setDashboardData(res.data);
console.log("Dashboard Data:", res.data);
const cardDataArray = mapApiDataToCards(res.data);
setCards(cardDataArray);
} catch (error) {

View File

@ -28,13 +28,9 @@ const ShowDocs = () => {
);
};
console.log(selectedDocs, "selectedDocsselectedDocs")
console.log(selectedDocs.length, "LENGTHselectedDocs")
// Handle button click to update Redux state
const handleUpdateSelectedDocs = () => {
const selectedDocuments = documents.filter((doc) => selectedDocs.includes(doc.id));
console.log(selectedDocuments, "selected Document Line 34 ShowDocs.tsx")
dispatch(updateSelectedDocuments({ documents: selectedDocuments }));
};

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

@ -47,6 +47,9 @@ const cards = [
const StartSection = () => {
const navigate = useNavigate();
const dispatch = useDispatch<AppDispatch>()
const [activeAccountId, setActiveAccountId] = useState<string | null>(
JSON.parse(sessionStorage.getItem('activeAccountId') || 'null')
);
const user = useSelector((state: RootState) => state.user);
if (!user.account || user.account === null) {
@ -81,6 +84,35 @@ const StartSection = () => {
// }
// }, [])
// Listen for sessionStorage changes
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === 'activeAccountId') {
const newActiveAccountId = e.newValue ? JSON.parse(e.newValue) : null;
setActiveAccountId(newActiveAccountId);
}
};
// Listen for storage events (works for changes from other tabs)
window.addEventListener('storage', handleStorageChange);
// Custom event listener for same-tab changes
const handleCustomStorageChange = (e: CustomEvent) => {
if (e.detail.key === 'activeAccountId') {
setActiveAccountId(e.detail.newValue);
}
};
window.addEventListener('sessionStorageChange', handleCustomStorageChange as EventListener);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('sessionStorageChange', handleCustomStorageChange as EventListener);
};
}, []);
return (
<section className="px-3 py-2 w-full mt-2">
<h2 className="text-sm font-semibold text-gray-800 px-1 pb-2">
@ -93,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 />
<TransactionDataTable activeAccountId={activeAccountId}/>
</section>
<section className="w-full">
{/* <section className="w-full">
<TemplateTable />
</section>
</section> */}
</div>
</section>

View File

@ -37,7 +37,6 @@ const UploadDoc: React.FC = () => {
dispatch(uploadDocuments(formData))
.unwrap()
.then((res) => {
console.log("Documents uploaded", res);
// toast.dismiss();
// toast.info("📄 Documents uploaded!", {
// position: "bottom-right",

View File

@ -47,8 +47,8 @@ type Signer = {
const SignersList: React.FC<{ signers: Signer[] }> = ({ signers }) => {
return (
// <div className="bg-white/60 rounded-md shadow-sm border border-gray-100 ">
<div className="p-6 ">
<div className="flex items-center justify-evenly mb-2">
<div className="p-2 ">
<div className="flex items-center justify-evenly mb-1">
<h3 className="text-lg font-semibold text-gray-800 flex items-center gap-2 ">
<FaUsers className="text-blue-600" />
Signature Status
@ -58,7 +58,7 @@ const SignersList: React.FC<{ signers: Signer[] }> = ({ signers }) => {
</span>
</div>
<div className="space-y-3 max-h-[20vh] overflow-y-auto no-scrollbar">
<div className="space-y-3 max-h-[24vh] overflow-y-auto no-scrollbar">
{signers.map((signer) => (
<div key={signer.id} className="text-xs mx-auto flex items-center gap-4 p-3 w-[70vh] bg-gradient-to-br from-gray-50 to-blue-100 rounded-lg">
<div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center text-blue-600 font-medium">
@ -201,7 +201,6 @@ const SigningOrderDiagram: React.FC<{ signers: Signer[] }> = ({ signers }) => {
const DocumentSubmissionOptions = () => {
const location = useLocation();
const [status, setStatus] = useState(null);
console.log("location.pathname", location.pathname, status)
const { accountId, transactionId } = useParams<{ accountId: string, transactionId: string }>();
const [showConfetti, setShowConfetti] = React.useState(true)
if (!accountId || !transactionId) {
@ -216,7 +215,6 @@ const DocumentSubmissionOptions = () => {
const selectedRecipients = useSelector((state: RootState) => state.selectedRecipients.recipients);
// const selectedDocuments = useSelector((state: RootState) => state.selectedDocuments.selectedDocuments)
const selectedDocuments = useSelector((state: RootState) => state.documents.documents)
console.log('Line 218', selectedDocuments)
const [transactionData, setTransactionData] = useState({})
@ -267,10 +265,6 @@ const DocumentSubmissionOptions = () => {
}
}, [showConfetti]);
console.log("History length:", window.history.length);
// Step 1: Fetch transaction status
useEffect(() => {
const fetchTransaction = async () => {

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,11 +39,10 @@ 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);
console.log(jsonData, "Kaboom");
if (jsonData.isComplete) {
isCompleted = true;
@ -87,8 +86,6 @@ const DocumentCard: React.FC<DocumentCardProps> = ({ id, name, isCompleted , tra
};
}, [id]);
console.log(isCompleted, "line 118")
const radius = 28
const circumference = 2 * Math.PI * radius
const offset = circumference - (progress / 100) * circumference
@ -103,7 +100,6 @@ const DocumentCard: React.FC<DocumentCardProps> = ({ id, name, isCompleted , tra
if (res.status === 202) {
dispatch(deleteDocument(docId));
setDocumentDel({ docId: null, isDel: false });
console.log("Document deleted successfully");
}
}

View File

@ -31,7 +31,7 @@ const ProcessStepOne = () => {
const templateId = useParams<{ templateId: string }>().templateId;
let { accountId, transactionId } = useParams<{ accountId: string, transactionId: string }>();
const [searchParams] = useSearchParams();
console.log("searchParams", searchParams.get('useTemplate'))
const isTamplate = searchParams.get('useTemplate')
const navigate = useNavigate();
@ -47,22 +47,11 @@ 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)
const [editRecipientCurrentEmail, setEditRecipientCurrentEmail] = useState('')
console.log()
const userData = useSelector((state: RootState) => state.user)
// ProcessStepOne.tsx
const topRef = useRef<HTMLDivElement | null>(null);
@ -83,15 +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>([]);
console.log("selectedRecipients", selectedRecipients)
useEffect(() => {
// <<<<<<< HEAD
// Fetching Transaction Details - START
(async () => {
try {
const res = await api.get(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`);
@ -105,38 +88,27 @@ const ProcessStepOne = () => {
{ subject: res.data.subject ? res.data.subject : "Documents for Signature", message: res.data.message ? res.data.message : "" }
)
// console.log("setTransactionDetails",res.data)
} catch (e) {
console.log("Error - transactions details")
}
})()
// Fetching Transaction Details - END
// =======
// (async () => {
// const res = await api.get(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`)
// console.log(res.data);
// })()
// >>>>>>> origin/main
// (async () => {
// const res = await api.get(`/api/accounts/${accountId}/${transactionTemplateToggle}/${transactionId}`)
// console.log(res.data);
// })()
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) => {
@ -172,7 +144,6 @@ const ProcessStepOne = () => {
if (SignTypeEnum.selfSign === signType) formError.recipients = false;
if (formError.documents || formError.recipients || formError.subject || formError.recipientEmailAndLastName) {
console.log(selectedDocuments, 'line 193')
toast.dismiss();
toast.error(`${formError.documents ? "Add Document" : ""}
${(formError.documents && formError.recipients) ? " | " : ""}
@ -216,10 +187,17 @@ const ProcessStepOne = () => {
dispatch(showLoader("Processing Recipients..."));
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,
provideOwnTags: userData.email === recipient.email ? true : false,
provideOwnTags: userData.email === recipient.email && (recipient.routingOrder ?? 1) === minRoutingOrder ? true : false,
type: recipient.type,
firstName: recipient.firstName,
lastName: recipient.lastName,
@ -249,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 = [{
@ -274,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 {
@ -288,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..."));
@ -298,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) {
@ -398,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
@ -447,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>
@ -479,7 +454,7 @@ const ProcessStepOne = () => {
{/* Message */}
<div className='flex flex-col'>
<label className='text-sm font-medium text-[var(--greyTextCol)] mb-1'>Message for Signers</label>
<label className='text-sm font-medium text-[var(--greyTextCol)] mb-1'>Message</label>
<textarea
rows={4}
value={emailDtls.message}

View File

@ -26,21 +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);
console.log("recipients.length in AddCase", 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)
@ -59,10 +58,6 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
type: false,
});
console.log(recipient)
useEffect(() => {
if (openContactModal) {
if (topRef?.current) {
@ -82,9 +77,9 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
(r.email && r.email === editRecipient?.email)
);
});
console.log("Line 83", exists)
if (editCase === "Edit" && editRecipient) {
console.log("editRecipientAdd", editRecipient)
if (!exists) {
// Recipient was deleted -> reset
setEditCase('');
@ -221,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(),
@ -269,6 +266,7 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
const handleFocus = async (field: "firstName" | "lastName" | "email") => {
setManualFocusTriggered(true);
setOpenContactModal(true);
setActiveField(field);
@ -278,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);
@ -296,11 +294,11 @@ const RecipientAddCard = ({ transactionTemplateToggle, editRecipient, editCase,
useDebouncedEffect(() => {
console.log("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 });
@ -320,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);
@ -486,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 });
@ -600,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,14 +2,14 @@ import { useNavigate } from "react-router-dom";
type PropsType = {
setShowSelfSignWarnModal: (val: boolean) => void;
onConfirm: () => void;
onConfirm?: () => void;
};
const SelfSignWarnModal = ({ setShowSelfSignWarnModal }: PropsType) => {
const navigate = useNavigate()
return (
<div className="fixed inset-0 backdrop-blur-sm flex items-center justify-center z-50">
<div className="fixed inset-0 backdrop-blur-sm bg-black/30 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl p-6 w-100">
<h3 className="text-lg font-medium text-gray-800 mb-4">Confirm Self Sign</h3>
<p className="text-gray-600 mb-6">

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[]
@ -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

@ -83,7 +83,10 @@ const FieldList: React.FC<FieldListProps> = ({ color, recipientId, recipientIndx
.then((res) => {
const priorityOrder = ['SIGNATURE', 'INITIALS', 'STAMP'];
const data = res.data;
const data = res.data.filter((obj, indx) => {
if (obj.type === "STAMP" || obj.type === "RADIO" || obj.type === "CHECKBOX" || obj.type === "ATTACHMENT") return false
return true
});
// Separate prioritized and other tags
const prioritized = data.filter((tag: any) =>

View File

@ -3,12 +3,13 @@ import { RootState } from '../../../store/store';
import { useDispatch, useSelector } from 'react-redux';
import FieldList from './FieldList';
import { addColorsToRecipient, fetchRecipients, toggleToTemplates, TRANSACTION_TEMPLATE_TOGGLE } from '../../../store/slices/selectedRecipientsSlice';
import { addColorsToRecipient, fetchRecipients, recipientType, toggleToTemplates, TRANSACTION_TEMPLATE_TOGGLE } from '../../../store/slices/selectedRecipientsSlice';
import { IoCheckmark } from 'react-icons/io5'
import { MdKeyboardArrowDown } from 'react-icons/md'
import { MdKeyboardArrowDown, MdOutlineNavigateNext } from 'react-icons/md'
import { useParams } from 'react-router-dom';
import { fetchDocuments } from '../../../store/slices/documentSlice';
import { GrFormPrevious } from 'react-icons/gr';
interface LeftSideBarProps {
isFields: boolean;
@ -36,6 +37,8 @@ const LeftSideBar: React.FC<LeftSideBarProps> = ({ isFields, selectedRecipientIn
const selectedRecipients = useSelector((state: RootState) => state.selectedRecipients.recipients)
const selectedDocuments = useSelector((state: RootState) => state.documents.documents)
const [currentPage, setCurrentPage] = useState(0);
useEffect(() => {
if (selectedRecipients.length === 0) {
dispatch(fetchRecipients({ accountId, transactionId }));
@ -94,6 +97,7 @@ const LeftSideBar: React.FC<LeftSideBarProps> = ({ isFields, selectedRecipientIn
<div
className={`absolute w-full shadow-md rounded-md mt-1 px-2 py-1 z-20 bg-white ${dropDownToggle ? '' : 'hidden'}`}>
{selectedRecipients.length && selectedRecipients.map((recipient, indx) => {
if (recipient.type === recipientType.CC) return null; // Skip CC recipients
return (<div
key={indx}
className='flex items-center justify-between gap-2 w-full p-2 text-xs rounded-sm cursor-pointer hover:bg-slate-100'
@ -151,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="" />
}
@ -165,18 +169,57 @@ const LeftSideBar: React.FC<LeftSideBarProps> = ({ isFields, selectedRecipientIn
{
dropDownTogglePage === 'pageDropDown' + indx &&
<div className='my-1 flex justify-center items-center gap-1 flex-wrap'>
{document.pages != undefined && document.pages.map((img, indx) => (
<a
href={"#" + document.id + indx}
className='max-w-max px-4 py-2 shadow cursor-pointer border-1 rounded-sm border-slate-200 hover:border-[var(--primary)] transition-all duration-300 bg-slate-300'
>
<p className='text-center text-xs text-slate-600'>{indx + 1}</p>
</a>
))}
<div className="my-1 flex justify-center items-center gap-2 flex-wrap">
{/* Prev Button */}
<a
href={"#" + document.id + (currentPage - 1)}
className={`cursor-pointer px-2 py-1 shadow rounded-sm text-sm bg-slate-200 hover:border-[var(--primary)] transition-all duration-300 ${currentPage === 0 ? "pointer-events-none opacity-50" : ""
}`}
onClick={(e) => {
if (currentPage === 0) e.preventDefault();
else setCurrentPage(currentPage - 1);
}}
>
<GrFormPrevious />
</a>
{/* Page Selector */}
<select
className="w-[58px] py-1 text-xs text-slate-400 outline-none"
value={currentPage}
onChange={(e) => {
const newPage = Number(e.target.value);
setCurrentPage(newPage);
window.location.hash = document.id +""+ newPage;
}}
>
{document.pages != undefined && document.pages.map((_, pageIndex) => (
<option key={pageIndex} value={pageIndex}>
{pageIndex + 1}
</option>
))}
</select>
<span className="text-xs text-slate-600">
/ {document.pages?.length}
</span>
{/* Next Button */}
<a
href={"#" + document.id + (currentPage + 1)}
className={`cursor-pointer px-2 py-1 shadow rounded-sm text-sm bg-slate-200 hover:border-[var(--primary)] transition-all duration-300 ${currentPage === document.pages?.length - 1 ? "pointer-events-none opacity-50" : ""
}`}
onClick={(e) => {
if (currentPage === document.pages?.length - 1) e.preventDefault();
else setCurrentPage(currentPage + 1);
}}
>
<MdOutlineNavigateNext />
</a>
</div>
}
</div>
)
})}

View File

@ -8,7 +8,7 @@ import { IoIosDocument } from 'react-icons/io'
import { LuTableOfContents } from 'react-icons/lu'
import { MdKeyboardArrowDown } from 'react-icons/md'
import { RiResetRightLine } from 'react-icons/ri'
import { fetchRecipients, toggleToTemplates, TRANSACTION_TEMPLATE_TOGGLE } from '../../../store/slices/selectedRecipientsSlice'
import { fetchRecipients, recipientType, toggleToTemplates, TRANSACTION_TEMPLATE_TOGGLE } from '../../../store/slices/selectedRecipientsSlice'
import { fetchDocuments } from '../../../store/slices/documentSlice'
import { useNavigate, useParams } from 'react-router-dom'
import { Bounce, toast } from 'react-toastify'
@ -91,7 +91,8 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
let userEmailPresent = {
present: false,
routingOrder: 0,
recipientId: 0
recipientId: 0,
type: recipientType.CC
};
// Getting Minimum RoutingOrder
for (let i = 0; i < selectedRecipients.length; i++) {
@ -104,10 +105,11 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
userEmailPresent.present = true;
userEmailPresent.routingOrder = recipient.routingOrder;
userEmailPresent.recipientId = recipient.id;
userEmailPresent.type = recipient.type;
}
}
if (userEmailPresent.present && userEmailPresent.routingOrder === minRoutingOrder) {
if (userEmailPresent.present && userEmailPresent.routingOrder === minRoutingOrder && userEmailPresent.type !== recipientType.CC && userEmailPresent.type !== recipientType.INPERSONSIGNER) {
setSelfUserSign({ sign: true, recipientId: userEmailPresent.recipientId })
}
}
@ -126,7 +128,7 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
setTimeout(() => {
if (transactionTemplateToggle === TRANSACTION_TEMPLATE_TOGGLE.TRANSACTIONS) {
if (isSignSend) {
// navigate(`./../../../sign/${selfUserSign.recipientId}`,{ replace: true });
// window.open(`./../../../sign/${selfUserSign.recipientId}`, "_self");
}
else {
// navigate(`/document-completion-screen/${accountId}/${transactionId}`, { replace: true })
@ -167,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;
@ -221,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)}
@ -281,7 +254,6 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
<MdKeyboardArrowDown className={`${nav2DocToggle ? 'rotate-180' : ''} transition-all`} />
</div>
<div
className={`absolute max-w-max shadow rounded-md mt-1 px-2 py-1 z-20 bg-white ${nav2DocToggle ? '' : 'hidden'}`}>
@ -312,7 +284,7 @@ const NavTwo: React.FC<NavTwoProps> = ({ transactionSaving, isFields, setIsField
return (<div key={indx} className='flex items-center justify-between gap-2 w-full p-2 text-xs rounded-sm cursor-default'>
<div className='flex items-center gap-1.5'>
<p className='w-3 h-3 rounded-sm' style={{ background: recipient.color }}></p>
<p className='whitespace-nowrap overflow-hidden text-ellipsis max-w-[12ch]'>{recipient.firstName} {recipient.lastName}</p>
<p className='whitespace-nowrap overflow-hidden text-ellipsis max-w-[22ch]'>{recipient.type + " | "} {recipient.firstName} {recipient.lastName}</p>
</div>
</div>)
})}

View File

@ -34,9 +34,6 @@ const ProcessStepTwo = () => {
}, 800)
}, [])
return (
<div className={`min-w-full relative h-screen bg-slate-100 overflow-hidden ${(globalLoader.isLoading) ? 'pointer-events-none' : ''}`}>
<NavTwo transactionSaving={transactionSaving} isFields={isFields} setIsFields={setIsFields} isSend={isSend} setIsSend={setIsSend} />

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,30 +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";
// 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[]
@ -33,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 {
@ -115,124 +102,8 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
const [styleOpen, setStyleOpen] = useState(false);
const handlePropertyChange = (changeTo: string, changeWith: string | boolean | number | StylesInterface, is24Hrs = null) => {
console.log("changeTo", changeTo, "changeWith", changeWith)
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) => {
@ -255,7 +126,6 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
// })
setDroppedItems((prev) => {
return (prev.map((item, idx) => {
console.log(prev, "Prev lIne 258")
if (idx === selTagIndx) {
return { ...item, [changeTo]: changeWith, update: true }
}
@ -267,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);
@ -292,7 +146,7 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
if (selectedTag.label === TagsTypes.TEXT && !("multiLine" in selectedTag)) {
handlePropertyChange("multiLine", true);
}
}, [])
}, [selectedTag])
const handleDecimalPlace = (e: React.ChangeEvent<HTMLInputElement>) => {
const val = Number(e.target.value)
@ -306,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;
@ -334,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) => {
@ -469,37 +285,26 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
className: ''
}
console.log(selectedType, "line 434");
return (
<>
{/* 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 &&
@ -527,6 +332,15 @@ const RightSideBar: React.FC<DroppedItemProps> = ({ droppedItems, selectedTag, s
handlePropertyChange={handlePropertyChange} />
}
{/* Mask Type */}
{
selectedTag.type.toLowerCase() === TagsTypes.TEXT &&
<TextValueFIll
value={selectedTag.value ?? ""}
multiLine={selectedTag.multiLine ?? false}
handlePropertyChange={handlePropertyChange}
/>
}
{/* TEMPORAL DATE FORMAT - START */}
{
@ -572,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,7 +1,9 @@
import { MdKeyboardArrowDown } from 'react-icons/md';
import { DROPDOWNTOGGLE, MASKCHARACTER, MASKTYPE, NUMBER, SELECT, TEMPORAL, TEXT } from './RightSideBar';
import { DroppedItem, TagsTypes } from '../../../../utlity/types';
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 {
selectedType: any;
@ -17,8 +19,6 @@ const CommonAttrDropDown: React.FC<CommonAttrDropDownInt> = ({ selectedType, sel
let subType = "";
let subTypeKey = ""
console.log(selectedType, selectedTag, "line 20");
switch (selectedTag.type.toLowerCase()) {
case "number":
if (selectedTag.decimalPlace === undefined) {
@ -36,7 +36,6 @@ const CommonAttrDropDown: React.FC<CommonAttrDropDownInt> = ({ selectedType, sel
}
break;
case "text":
console.log("Line 444", selectedTag);
if (selectedTag.multiLine === undefined) {
subType = TEXT.PARAGRAPH
} else if (selectedTag.multiLine) {
@ -73,8 +72,6 @@ const CommonAttrDropDown: React.FC<CommonAttrDropDownInt> = ({ selectedType, sel
break;
}
console.log(selectedTag, "line 63");
return (
<div className="flex flex-col">
<label htmlFor="" className="">Type</label>
@ -90,9 +87,6 @@ const CommonAttrDropDown: React.FC<CommonAttrDropDownInt> = ({ selectedType, sel
<div className="shadow bg-slate-100 mt-1 border-[1px] border-slate-100 rounded">
{Object.keys(selectedType).map((val, indx) => {
console.log(selectedType, val, "Line 90")
let value = val.toLowerCase() as keyof typeof selectedType | number | boolean;
let isCurrency = false;
let isPassword = false;
@ -133,8 +127,6 @@ const CommonAttrDropDown: React.FC<CommonAttrDropDownInt> = ({ selectedType, sel
}
// Handling TEXT - END
console.log(subTypeKey, subType, value, "line 1223");
return (
<div
key={indx}
@ -162,8 +154,27 @@ const CommonAttrDropDown: React.FC<CommonAttrDropDownInt> = ({ selectedType, sel
}
handlePropertyChange(subTypeKey, value as boolean);
}
else {
} else if (selectedTag.type.toLowerCase() === TagsTypes.TEMPORAL) {
handlePropertyChange(subTypeKey, selectedType[val as keyof typeof selectedType]);
if (subTypeKey === "dateFormat") {
let format = null;
switch (value) {
case "date":
format = dateFormats[0].format;
break;
case "time":
format = timeFormats[0].format;
break;
case "date_time":
format = dateFormats[0].format + " " + timeFormats[0].format;
break;
default:
format = dateFormats[0].format;
}
handlePropertyChange("format", format as string);
}
} else {
handlePropertyChange(subTypeKey, selectedType[val as keyof typeof selectedType]);
}
}}

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,7 +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 { RootState } from '../../../../../store/store';
import { recipientType } from '../../../../../store/slices/selectedRecipientsSlice';
interface SelectedRecipientsIntr {
@ -67,6 +68,7 @@ const RecipientsAttrCon: React.FC<RecipientsAttrConIntr> = ({ selectedRecipientI
<div
className={`absolute w-full shadow-md rounded-md mt-1 px-2 py-1 z-20 bg-white ${dropDownToggle ? '' : 'hidden'}`}>
{selectedRecipients.length && selectedRecipients.map((recipient, indx) => {
if (recipient.type === recipientType.CC) return null; // Skip CC recipients
return (<div
key={indx}
className='flex items-center justify-between gap-2 w-full p-2 text-xs rounded-sm cursor-pointer hover:bg-slate-100'

View File

@ -52,7 +52,6 @@ const SelectTagAttr: React.FC<SelectTagAttrInt> = ({ options, selTagKey, selTagI
};
}
console.log("New droppedItems state:", newState);
return newState;
});
}

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,
@ -25,20 +25,29 @@ interface TemporalDateAttrInt {
const TemporalDateAttr: React.FC<TemporalDateAttrInt> = ({ dateFormat, format, selectedTag, dropDownToggle, setDropDownToggle, handlePropertyChange }) => {
console.log(dateFormat, format, "dateFormat Line 26", selectedTag)
let is24HourFormat = true
const [is24Hrs, setIs24Hrs] = useState<boolean>(true);
if (selectedTag.format && selectedTag.format.split(/hh|mm/).length > 0) {
if ((selectedTag.format.split(/:mm/)[0]).at(-1) === "h") {
is24HourFormat = false;
}
}
const [is24Hrs, setIs24Hrs] = useState<boolean>(is24HourFormat);
const handleIs24HrsClick = (checked: boolean) => {
if (dateFormat === TEMPORAL.TIME) {
if (!checked) {
handlePropertyChange("format", timeFormats[1].format, is24Hrs)
handlePropertyChange("format", timeFormats[1].format, !is24Hrs)
} else {
handlePropertyChange("format", timeFormats[0].format, is24Hrs)
}
}
else if (dateFormat === TEMPORAL.DATE_TIME) {
handlePropertyChange("format", (format.split(" ").slice(0, -1).join(" ")), !is24Hrs)
const timeFormat = format = timeFormats[checked ? 0 : 1].format;
const dateFormat = selectedTag.format && selectedTag.format.split(/hh|HH/)[0]
handlePropertyChange("format", dateFormat+" "+timeFormat, checked ? is24Hrs : !is24Hrs)
}
setIs24Hrs(checked)
}
@ -87,12 +96,12 @@ const TemporalDateAttr: React.FC<TemporalDateAttrInt> = ({ dateFormat, format, s
let val = valObj["format"]
if (dateFormat === TEMPORAL.DATE_TIME) {
if (is24Hrs) {
val = val + " " + timeFormats[0].format;
val = val+" "+timeFormats[0].format;
} else {
val = val + " " + timeFormats[1].format;
val = val+" "+timeFormats[1].format;
}
}
console.log('line 89', val)
return (
<div
key={indx}

View File

@ -0,0 +1,35 @@
import React, { useState } from 'react'
interface TextValueFIllProps {
value: string | number;
multiLine: boolean;
handlePropertyChange: (changeTo: string, changeWith: string | boolean | number) => void;
}
const TextValueFIll: React.FC<TextValueFIllProps> = ({ value = "", multiLine, handlePropertyChange }) => {
const [textValue, setTextValue] = useState<string | number>(value);
return (
<div className="flex flex-col">
<label htmlFor="textValue">Value</label>
{multiLine ?
<textarea
onBlur={() => handlePropertyChange("value", textValue)}
id="textValue"
value={textValue}
className="outline-none border-1 rounded px-2 py-1 border-slate-200"
onChange={e => setTextValue(e.target.value)}
></textarea>
: <input
onBlur={() => handlePropertyChange("value", textValue)}
id="textValue"
value={textValue}
className="outline-none border-1 rounded px-2 py-1 border-slate-200"
onChange={e => setTextValue(e.target.value)}
/>
}
</div>
)
}
export default TextValueFIll

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

@ -4,8 +4,6 @@ import { useParams } from 'react-router-dom'
const PageGuard = () => {
const allowedPages = ["settings", "contacts"]
console.log("Allowed Pages: ", allowedPages)
const {page1} = useParams<{page1: string}>()
if (page1 && !allowedPages.includes(page1)) {
return <div>Access Denied</div>

View File

@ -9,7 +9,7 @@ import AsideSection from "./AsideSection";
import Signature from "./Signature/Signature";
import { Bounce, toast } from "react-toastify";
import AccountNav from "../accounts/AccountNav";
import ContactForm , {ContactData} from "./ContactForm";
import ContactForm, { ContactData } from "./ContactForm";
// Define the shape of state object
interface Account {
@ -43,9 +43,7 @@ interface AccountOption {
const Setting = () => {
const { page1 } = useParams<{ page1: string }>();
console.log("page1", page1)
const location = useLocation();
console.log("location", location)
const navigate = useNavigate();
const [activeAccountId, setActiveAccountId] = useState<string | null>(
@ -310,7 +308,6 @@ const Setting = () => {
// Set initial subsection when component mounts or activeTab changes
useEffect(() => {
const subSections = getSubSections(activeTab);
console.log("subSections", subSections)
const hash = location.hash.replace('#', '');
if (subSections.length > 0) {
@ -345,23 +342,19 @@ const Setting = () => {
let res;
let toastMesaage;
if (action === 'create') {
console.log('Creating account:', data);
const payloadAccount = {
name: data.accountName
}
res = await api.post(`/api/user/accounts`, payloadAccount)
console.log("resAccountName", res)
if (res.status === 201) {
toastMesaage = `${action.toUpperCase()} Created Successfull...!`
}
} else if (action === 'invite') {
console.log('Inviting user:', data);
const payloadInvite = {
email: data.email,
role: data.role
}
res = await api.post(`/api/accounts/${data.i_accountName}/invite`, payloadInvite)
console.log("InviteNAme", res)
toastMesaage = "Invite Successfull...!"
}
@ -392,7 +385,7 @@ const Setting = () => {
const handleContactSubmit = async (data: ContactData) => {
try {
setCreateAndInviteLoader(true);
const res = await api.post(`/api/accounts/${activeAccountId}/contacts`, [data]);
const res = await api.post(`/api/accounts/${activeAccountId}/contacts`, [data]);
if (res.status === 200) {
toast.success('Contact created successfully!', {
position: "top-center",
@ -415,16 +408,16 @@ const Setting = () => {
{/* <SettingNav /> */}
{/* <AccountNav/> */}
<div className="bg-[#f9fafa] h-[calc(90vh-20px)] flex flex-col mt-2">
{/* Main Navigation Tabs */}
<div className="sticky top-0 z-10 bg-white border-b border-gray-200 px-8 pt-5">
<div className="flex gap-6">
{/* Tabs */}
<div className="sticky top-0 z-10 bg-white border-b border-gray-200 px-4 md:px-6 lg:px-8 pt-4">
<div className="flex flex-wrap gap-4 md:gap-6">
{tabs.map((tab) =>
tab.type === page1 && (
<button
key={tab.id}
onClick={() => handleMainTabClick(tab.id)}
className={`cursor-pointer relative pb-3 text-sm font-medium transition-all duration-200
${activeTab === tab.id
${activeTab === tab.id
? "text-blue-600 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-blue-600"
: "text-gray-600 hover:text-blue-500"
}`}
@ -436,11 +429,12 @@ const Setting = () => {
</div>
</div>
{/* Content with Aside Navigation */}
<div className="flex mt-3 px-8 flex-1 min-h-0">
{/* Fixed Aside Navigation - Shows subsections of active tab */}
{activeTab === 'userProfile' &&
<section className="flex-shrink-0 mr-6 w-50 relative">
{/* Responsive Layout */}
<div className="flex-1 min-h-0 flex flex-col lg:flex-row px-4 md:px-6 lg:px-8 mt-3 gap-6">
{/* Sidebar (hidden on small, shown on lg) */}
{activeTab === 'userProfile' && (
<section className="hidden lg:block flex-shrink-0 w-56">
<div className="sticky top-6 z-20">
<AsideSection
activeSubSection={activeSubSection}
@ -450,8 +444,28 @@ const Setting = () => {
/>
</div>
</section>
}
{/* Scrollable Main Content */}
)}
{/* Sidebar as horizontal nav (only on mobile) */}
{activeTab === 'userProfile' && (
<section className="lg:hidden mb-4">
<div className="flex overflow-x-auto no-scrollbar gap-4 border-b pb-2">
{getSubSections(activeTab).map((sub) => (
<button
key={sub.id}
onClick={() => handleSubSectionClick(sub.id)}
className={`whitespace-nowrap text-sm font-medium px-2 py-1 rounded-md
${activeSubSection === sub.id ? "bg-blue-100 text-blue-600" : "text-gray-600"}
`}
>
{sub.label}
</button>
))}
</div>
</section>
)}
{/* Main Content */}
<div
ref={scrollContainerRef}
className="flex-1 min-w-0 overflow-y-auto no-scrollbar"
@ -460,6 +474,7 @@ const Setting = () => {
</div>
</div>
</div>
</>
)
}

View File

@ -107,17 +107,16 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
// Navigation items
const navigationItems = [
{ id: 'SELECT', label: 'SELECT', icon: <GrCheckboxSelected className="w-4 h-4" /> },
{ id: 'DRAW', label: 'DRAW', icon: <AiOutlineEdit className="w-5 h-5" /> },
{ id: 'UPLOAD', label: 'UPLOAD', icon: <AiOutlineUpload className="w-5 h-5" /> },
// { id: 'SELECT', label: 'SELECT', icon: <GrCheckboxSelected className="w-4 h-4" /> },
{ id: 'SELECT', label: 'SELECT', icon: <GrCheckboxSelected className="w-3 h-3 md:w-4 md:h-4" /> },
{ id: 'DRAW', label: 'DRAW', icon: <AiOutlineEdit className="w-3 h-3 md:w-4 md:h-4" /> },
{ id: 'UPLOAD', label: 'UPLOAD', icon: <AiOutlineUpload className="w-3 h-3 md:w-4 md:h-4" /> },
];
// Initialize form with editing signature data
useEffect(() => {
if (editingSignature) {
setFullName(`${editingSignature.firstName} ${editingSignature.lastName}`);
setInitials(`${editingSignature.firstName.slice(0, 1)}${editingSignature.lastName.slice(0, 1)}`);
setInitials((`${editingSignature.firstName.slice(0, 1)}${editingSignature.lastName.slice(0, 1)}`).toUpperCase());
setActiveTab(editingSignature.signatureType as 'SELECT' | 'DRAW' | 'UPLOAD');
// Set font for SELECT tab
@ -193,25 +192,41 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
const handleSubmit = async () => {
setIsSubmitting(true);
if (activeTab === 'DRAW' || activeTab === 'UPLOAD') {
if (!signatures.fullSignature || !signatures.initials) {
alert('Please provide both signature and initials');
setIsSubmitting(false);
return;
}
// Only validate for DRAW and UPLOAD
if ((activeTab === 'DRAW' || activeTab === 'UPLOAD') &&
(!signatures.fullSignature || !signatures.initials)) {
// alert('Please provide both signature and initials');
toast.error('Please provide both signature and initials in draw and upload case', {
position: "top-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: false,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
setIsSubmitting(false);
return;
}
try {
// Base payload
const payload = {
signatureType: activeTab,
signatureBase64: signatures.fullSignature,
initialsBase64: signatures.initials,
firstName: fullName.split(' ')[0] || user.firstName,
lastName: fullName.split(' ')[1] || user.lastName,
font: selectedSignature.style,
default: checked
};
// Only add signatures if not SELECT
if (activeTab !== 'SELECT') {
payload.signatureBase64 = signatures.fullSignature;
payload.initialsBase64 = signatures.initials;
}
let res;
if (isEditMode && editingSignature) {
// Update existing signature
@ -220,7 +235,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
signatureId: editingSignature.id
};
res = await api.put(`/api/user/signatures`, updatePayload);
console.log("handleUpdate", res);
toast.success("Signature Updated Successfully", {
position: "top-center",
@ -236,7 +250,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
} else {
// Create new signature
res = await api.post(`/api/user/signatures`, payload);
console.log("handleSubmit", res);
toast.success("Signature Created Successfully", {
position: "top-center",
@ -273,32 +286,57 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
}
};
// Fixed renderContent function for SELECT case with proper radio button styling
const renderContent = () => {
switch (activeTab) {
case 'SELECT':
return (
<div className="h-full flex flex-col ">
<div className="mb-6">
<h2 className="text-xl font-semibold text-gray-900 mb-2">Choose Signature Style</h2>
<p className="text-sm text-gray-600">Select from pre-designed signature styles</p>
<div className="h-full flex flex-col">
<div className="mb-1 md:mb-4 lg:mb-6 flex-shrink-0">
<h2 className="text-base md:text-lg lg:text-xl font-semibold text-gray-900 mb-1">Choose Signature Style</h2>
<p className="text-xs md:text-sm text-gray-600 hidden md:block">Select from pre-designed signature styles</p>
</div>
<div className="flex-1 overflow-y-auto">
<div className="space-y-4">
<div className="flex-1 min-h-0 overflow-y-auto no-scrollbar">
<div className="space-y-2 md:space-y-3 pb-2">
{signatureOptions.map((option) => (
<div key={option.id} className="flex items-center space-x-4 px-2 py-1 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
<div
key={option.id}
className={`flex items-center space-x-2 md:space-x-3 p-2 md:p-3 border rounded-lg transition-all duration-200 cursor-pointer ${selectedSignature.id === option.id
? 'border-gray-100 shadow-sm'
: 'border-gray-200 hover:bg-gray-50 hover:border-gray-300'
}`}
onClick={() => setSelectedSignature({ id: option.id, style: option.style })}
>
{/* Custom Radio Button */}
<div className="flex-shrink-0">
<div
className={`w-4 h-4 md:w-3 md:h-3 rounded-full border-2 flex items-center justify-center transition-all duration-200 ${selectedSignature.id === option.id
? 'border-gray-300 bg-blue-600'
: 'border-gray-300 bg-white hover:border-gray-400'
}`}
>
{selectedSignature.id === option.id && (
<div className="w-2 h-2 md:w-3 md:h-2 rounded-full bg-blue-500"></div>
)}
</div>
</div>
{/* Hidden native radio button for accessibility */}
<input
type="radio"
id={`signature-${option.id}`}
name="signature"
checked={selectedSignature.id === option.id}
onChange={() => setSelectedSignature({ id: option.id, style: option.style })}
className="w-4 h-4 text-blue-600 focus:ring-blue-500"
className="sr-only"
/>
<div className="flex-1 grid grid-cols-2 gap-2">
<div className=" border-gray-300 rounded-lg px-2 py-1 bg-white ">
<div className="text-xs text-gray-500 mb-2">Signed by:</div>
<div className={`text-lg ${option.style === 'cursive' ? 'font-serif italic' :
<div className="flex-1 min-w-0 grid grid-cols-1 md:grid-cols-2 gap-2 md:gap-3">
<div className="border border-gray-300 rounded-lg px-2 md:px-3 py-2 md:py-3 bg-white min-w-0">
<div className="text-xs text-gray-500 mb-1">Signed by:</div>
<div className={`text-sm md:text-base truncate ${option.style === 'cursive' ? 'font-serif italic' :
option.style === 'script' ? 'font-mono' :
option.style === 'elegant' ? 'font-serif' :
option.style === 'modern' ? 'font-sans tracking-wide' :
@ -306,13 +344,13 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
}`}>
{fullName || option.name}
</div>
<div className="text-xs text-gray-400 mt-2">
<div className="text-xs text-gray-400 mt-1 truncate">
dca3e646-62cd-4cc...
</div>
</div>
<div className=" rounded-lg px-2 py-2 bg-white ">
<div className="text-xs text-gray-500 mb-2">DS</div>
<div className={`text-2xl ${option.style === 'cursive' ? 'font-serif italic' :
<div className="border border-gray-300 rounded-lg px-2 md:px-3 py-2 md:py-3 bg-white min-w-0">
<div className="text-xs text-gray-500 mb-1">DS</div>
<div className={`text-lg md:text-xl truncate ${option.style === 'cursive' ? 'font-serif italic' :
option.style === 'script' ? 'font-mono' :
option.style === 'elegant' ? 'font-serif' :
option.style === 'modern' ? 'font-sans tracking-wide' :
@ -331,79 +369,73 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
case 'DRAW':
return (
<DrawSignatureCanvas
onSignatureChange={handleSignatureChange}
initialSignatures={isEditMode ? signatures : undefined}
/>
<div className="h-full">
<DrawSignatureCanvas
onSignatureChange={handleSignatureChange}
initialSignatures={isEditMode ? signatures : undefined}
/>
</div>
);
case 'UPLOAD':
return (
<div className="h-full flex flex-col">
<div className="mb-6">
<h2 className="text-xl font-semibold text-gray-900 mb-2">Upload Signature</h2>
<div className="mb-3 md:mb-4 lg:mb-6 flex-shrink-0">
<h2 className="text-base md:text-lg lg:text-xl font-semibold text-gray-900 mb-1">Upload Signature</h2>
<p className="text-xs md:text-sm text-gray-600 hidden md:block">Upload your signature images</p>
</div>
<div className="flex-1 overflow-y-auto">
<div>
<div className="grid grid-cols-12 gap-6">
{/* Upload 1 */}
<div className="col-span-8">
<label className="block text-sm font-medium text-gray-700 mb-2">Full Signature</label>
<label htmlFor="upload1" className=" border-2 border-dashed border-gray-300 rounded-lg h-62 flex items-center justify-center bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors">
{preview1 ? (
<img src={preview1} alt="Signature Preview" className="max-h-44 object-contain" />
) : (
<div className="text-center">
<MdCloudUpload className="mx-auto h-12 w-12 text-gray-400 mb-3" />
<p className="text-sm text-gray-500 mb-1">Click to upload or drag and drop</p>
<p className="text-xs text-gray-400">PNG, JPG, GIF up to 10MB</p>
</div>
)}
</label>
<input
id="upload1"
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleImageChange(e, setFile1, setPreview1, "fullSignature")}
/>
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
<div className="grid grid-cols-1 lg:grid-cols-12 gap-3 md:gap-4 pb-2">
{/* Upload 1 - Full Signature */}
<div className="lg:col-span-8">
<label className="block text-xs md:text-sm font-medium text-gray-700 mb-2">Full Signature</label>
<label htmlFor="upload1" className="block border-2 border-dashed border-gray-300 rounded-lg h-32 md:h-40 lg:h-48 xl:h-56 flex items-center justify-center bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors">
{preview1 ? (
<img src={preview1} alt="Signature Preview" className="max-h-full max-w-full object-contain p-2" />
) : (
<div className="text-center px-4">
<MdCloudUpload className="mx-auto h-6 w-6 md:h-8 md:w-8 lg:h-10 lg:w-10 text-gray-400 mb-2" />
<p className="text-xs md:text-sm text-gray-500 mb-1">Click to upload or drag and drop</p>
<p className="text-xs text-gray-400">PNG, JPG, GIF up to 10MB</p>
</div>
)}
</label>
<input
id="upload1"
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleImageChange(e, setFile1, setPreview1, "fullSignature")}
/>
</div>
{/* Upload 2 */}
<div className="col-span-4">
<label className="block text-sm font-medium text-gray-700 mb-2">Initials</label>
<label htmlFor="upload2" className=" border-2 border-dashed border-gray-300 rounded-lg h-62 flex items-center justify-center bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors">
{preview2 ? (
<img src={preview2} alt="Initials Preview" className="max-h-44 object-contain" />
) : (
<div className="text-center">
<MdCloudUpload className="mx-auto h-8 w-8 text-gray-400 mb-2" />
<p className="text-xs text-gray-500">Upload initials</p>
</div>
)}
</label>
<input
id="upload2"
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleImageChange(e, setFile2, setPreview2, "initials")}
/>
</div>
{/* Upload 2 - Initials */}
<div className="lg:col-span-4">
<label className="block text-xs md:text-sm font-medium text-gray-700 mb-2">Initials</label>
<label htmlFor="upload2" className="block border-2 border-dashed border-gray-300 rounded-lg h-32 md:h-40 lg:h-48 xl:h-56 flex items-center justify-center bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors">
{preview2 ? (
<img src={preview2} alt="Initials Preview" className="max-h-full max-w-full object-contain p-2" />
) : (
<div className="text-center px-2">
<MdCloudUpload className="mx-auto h-5 w-5 md:h-6 md:w-6 lg:h-8 lg:w-8 text-gray-400 mb-2" />
<p className="text-xs md:text-sm text-gray-500 mb-1">Upload initials</p>
<p className="text-xs text-gray-400 hidden md:block">PNG, JPG, GIF</p>
</div>
)}
</label>
<input
id="upload2"
type="file"
accept="image/*"
className="hidden"
onChange={(e) => handleImageChange(e, setFile2, setPreview2, "initials")}
/>
</div>
</div>
</div>
</div>
);
// case 'SELECT':
// return (
// <div className="h-full flex flex-col">
// <div className="mb-6">
// <h2 className="text-xl font-semibold text-gray-900 mb-2">Select Signature</h2>
// </div>
// </div>
// );
default:
return null;
}
@ -412,7 +444,7 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
const getUserDetails = async () => {
try {
let res = await api.get(`/api/user/details`);
console.log("getuser", res);
let currUser = res?.data;
setUser(currUser);
@ -430,25 +462,147 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
getUserDetails();
}, []);
return (
<div className="fixed inset-0 backdrop-blur-sm bg-opacity-50 bg-black/30 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-md shadow-xl w-full max-w-[80vw] h-[80vh] flex relative">
{/* Sidebar Navigation */}
<div className="w-64 bg-gray-50 rounded-l-lg border-r border-gray-200 flex flex-col">
{/* Header */}
<div className="px-4 py-4 border-b border-gray-200">
<div className="flex items-center space-x-3">
<div className='px-1 py-1'>
<h3 className="text-md font-semibold text-gray-900">Add Signature </h3>
<p className="text-xs text-gray-500">Create your digital signature</p>
return (
<div className="fixed inset-0 backdrop-blur-sm bg-opacity-50 bg-black/30 flex items-center justify-center z-50 p-2 md:p-4">
<div className="bg-white rounded-md shadow-xl w-full h-full md:max-w-[95vw] lg:max-w-[85vw] xl:max-w-[80vw] md:max-h-[95vh] lg:max-h-[90vh] flex flex-col md:flex-row relative overflow-hidden ">
{/* Mobile Navigation - Fixed at top on mobile only */}
<div className="md:hidden flex-1 flex flex-col min-h-0">
{/* Scrollable area (mobile: inputs + nav + content) */}
<div className="flex-1 min-h-0 overflow-y-auto no-scrollbar">
<div className="px-3 lg:px-6 py-2 border-b border-gray-200 flex-shrink-0">
<h3 className="text-sm font-semibold text-gray-900">
{isEditMode ? 'Edit Signature' : 'Add Signature'}
</h3>
</div>
{/* Mobile Inputs */}
<div className="md:hidden w-full bg-white border-b border-gray-200 flex-shrink-0 px-3 py-2">
<div className="grid grid-cols-3 gap-2">
<div className='col-span-2'>
<label className="block text-xs font-medium text-gray-700 mb-1">
Full Name
</label>
<input
type="text"
value={fullName}
onChange={(e) => setFullName(e.target.value)}
placeholder="Enter full name"
className="w-full px-2 py-2 text-xs border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
<div className='col-span-1'>
<label className="block text-xs font-medium text-gray-700 mb-1">
Initials
</label>
<input
type="text"
value={initials}
onChange={(e) => setInitials(e.target.value)}
placeholder="Enter initials"
className="w-full px-2 py-2 text-xs border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
</div>
</div>
{/* Mobile Navigation - Sticky inside scroll */}
<div className="md:hidden w-full bg-gray-50 border-b border-gray-200 sticky top-0 z-20">
<div className="px-3 py-1.5">
<nav className="flex gap-1">
{navigationItems.map((item) => (
<button
key={item.id}
onClick={() => setActiveTab(item.id as 'SELECT' | 'DRAW' | 'UPLOAD')}
className={`flex-1 flex items-center justify-center space-x-1 px-2 py-2 text-xs font-medium rounded-lg transition-all duration-200 whitespace-nowrap ${activeTab === item.id
? 'bg-blue-50 text-blue-700 border border-blue-200 shadow-sm'
: 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
}`}
>
<span className={activeTab === item.id ? 'text-blue-600' : 'text-gray-400'}>
{item.icon}
</span>
<span className="hidden sm:block">{item.label}</span>
</button>
))}
</nav>
</div>
</div>
{/* Main Content */}
<div className="md:hidden p-3 md:p-4 lg:py-5 lg:px-5">
<div className="h-full min-h-[300px] md:min-h-[400px]">
{renderContent()}
</div>
</div>
</div>
{/* Form Inputs */}
<div className="px-6 py-2.5 border-b border-gray-200">
<div className="space-y-2">
{/* Checkbox - Fixed */}
<div className="px-3 md:px-4 lg:px-6 py-2 md:py-3 text-gray-700 border-t border-gray-100 flex-shrink-0">
<label className="inline-flex items-center cursor-pointer text-xs md:text-sm hover:text-gray-900 transition-colors">
<input
type="checkbox"
checked={checked}
onChange={toggleCheckbox}
className="sr-only"
/>
<div
className={`w-3 h-3 md:w-4 md:h-4 border rounded flex items-center justify-center mr-2 md:mr-3 transition-colors flex-shrink-0 ${checked
? 'bg-[var(--modalSubmitBG)] border-[var(--modalSubmitBG)]'
: 'bg-white border-gray-400 hover:border-gray-500'
}`}
>
{checked && <FiCheck className="text-white text-xs" />}
</div>
<span>Save as default signature</span>
</label>
</div>
{/* Footer Buttons - Fixed */}
<div className="p-3 md:p-4 lg:p-3 border-t border-gray-200 flex sm:flex-row justify-end gap-2 md:gap-3 flex-shrink-0">
<button
className="w-full sm:w-auto px-3 md:px-4 lg:px-6 py-2 md:py-3 text-xs md:text-sm font-medium rounded-md border border-gray-300 text-gray-700 hover:bg-gray-50 hover:border-gray-400 disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-200"
onClick={() => setShowAddSignature?.(false)}
disabled={isSubmitting}
>
CANCEL
</button>
<button
className="w-full sm:w-auto px-3 md:px-4 lg:px-6 py-2 md:py-3 text-xs md:text-sm font-medium rounded-md bg-gradient-to-br from-[var(--primary)] to-blue-600 text-white hover:opacity-90 hover:shadow-lg flex items-center justify-center gap-1 md:gap-2 disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-200"
onClick={handleSubmit}
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<FaSpinner className="animate-spin w-3 h-3 md:w-4 md:h-4" />
<span>{isEditMode ? 'UPDATING...' : 'CREATING...'}</span>
</>
) : (
<span>{isEditMode ? 'UPDATE SIGNATURE' : 'CREATE SIGNATURE'}</span>
)}
</button>
</div>
</div>
{/* Desktop Sidebar Navigation */}
<div className="hidden md:flex md:w-64 lg:w-72 xl:w-80 bg-gray-50 md:border-r border-gray-200 flex-col">
{/* Header - Fixed */}
<div className="px-4 lg:px-6 py-4 border-b border-gray-200 flex-shrink-0">
<h3 className="text-base lg:text-lg font-semibold text-gray-900">
{isEditMode ? 'Edit Signature' : 'Add Signature'}
</h3>
<p className="text-sm text-gray-500">
{isEditMode ? 'Update your digital signature' : 'Create your digital signature'}
</p>
</div>
{/* Form Inputs - Fixed */}
<div className="px-4 lg:px-6 py-4 border-b border-gray-200 flex-shrink-0">
<div className="grid grid-cols-1 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Full Name
@ -458,10 +612,9 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
value={fullName}
onChange={(e) => setFullName(e.target.value)}
placeholder="Enter full name"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Initials
@ -471,109 +624,94 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
value={initials}
onChange={(e) => setInitials(e.target.value)}
placeholder="Enter initials"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
</div>
</div>
</div>
{/* Navigation Menu */}
<div className="flex-1 px-6 py-2.5">
<nav className="space-y-2">
{/* Navigation Menu - Fixed */}
<div className="px-4 lg:px-6 py-4 flex-shrink-0">
<nav className="flex flex-col gap-2">
{navigationItems.map((item) => (
<button
key={item.id}
onClick={() => setActiveTab(item.id as 'SELECT' | 'DRAW' | 'UPLOAD')}
className={`w-full flex items-center space-x-3 px-2 py-2 text-sm font-medium rounded-lg cursor-pointer transition-colors ${activeTab === item.id
? 'bg-blue-50 text-blue-700 border border-blue-200'
className={`w-full flex items-center justify-start space-x-2 px-3 py-3 text-sm font-medium rounded-lg transition-all duration-200 whitespace-nowrap ${activeTab === item.id
? 'bg-blue-50 text-blue-700 border border-blue-200 shadow-sm'
: 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
}`}
>
<span className={activeTab === item.id ? 'text-blue-600' : 'text-gray-400'}>
{item.icon}
</span>
<span>{item.label}</span>
</button>
))}
</nav>
</div>
{/* Spacer for desktop */}
<div className="flex-1"></div>
</div>
{/* Main Content Area */}
<div className="flex-1 flex flex-col ">
{/* Header with close button */}
{/* Content */}
<div className="flex-1 py-5 px-5 overflow-hidden ">
{/* <button
onClick={() => setShowAddSignature?.(false)}
className="absolute top-2 right-3 p-2 hover:bg-gray-100 rounded-full transition-colors z-20"
>
<AiOutlineClose className="w-5 h-5 text-gray-500" />
</button> */}
{renderContent()}
<div className="hidden flex-1 md:flex flex-col min-h-0">
{/* Content - Scrollable */}
<div className="flex-1 min-h-0 p-3 md:p-4 lg:py-5 lg:px-5 overflow-y-auto no-scrollbar">
<div className="h-full min-h-[300px] md:min-h-[400px]">
{renderContent()}
</div>
</div>
<div className="text-right px-6 py-1 text-white">
<label className="inline-flex items-center cursor-pointer group">
{/* Checkbox - Fixed */}
<div className="px-3 md:px-4 lg:px-6 py-2 md:py-3 text-gray-700 border-t border-gray-100 flex-shrink-0">
<label className="inline-flex items-center cursor-pointer text-xs md:text-sm hover:text-gray-900 transition-colors">
<input
type="checkbox"
checked={checked}
onChange={toggleCheckbox}
className="sr-only"
/>
{/* Custom checkbox UI */}
<div
className={`w-4 h-4 border rounded transition-all duration-300 flex items-center justify-center
${checked ? 'bg-[var(--modalSubmitBG)] border-[var(--modalSubmitBG)] scale-110' : 'bg-white border-gray-400'}
`}
className={`w-3 h-3 md:w-4 md:h-4 border rounded flex items-center justify-center mr-2 md:mr-3 transition-colors flex-shrink-0 ${checked ? 'bg-[var(--modalSubmitBG)] border-[var(--modalSubmitBG)]' : 'bg-white border-gray-400 hover:border-gray-500'
}`}
>
{checked && (
<FiCheck className="text-white text-sm transform scale-100 transition-transform duration-300" />
)}
{checked && <FiCheck className="text-white text-xs" />}
</div>
<p className="text-sm text-gray-700 opacity-80 ms-1">
Signature will be used by default.
</p>
<span>Save as default signature</span>
</label>
{/* Caption text below */}
</div>
{/* Footer Buttons in Main Area */}
<div className="p-4 border-t border-gray-200 flex justify-end gap-3">
{/* Footer Buttons - Fixed */}
<div className="p-3 md:p-4 lg:p-3 border-t border-gray-200 flex sm:flex-row justify-end gap-2 md:gap-3 flex-shrink-0">
<button
className="cursor-pointer px-4 py-2 text-sm font-medium rounded-md border border-gray-300 text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
className="w-full sm:w-auto px-3 md:px-4 lg:px-6 py-2 md:py-3 text-xs md:text-sm font-medium rounded-md border border-gray-300 text-gray-700 hover:bg-gray-50 hover:border-gray-400 disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-200"
onClick={() => setShowAddSignature?.(false)}
disabled={isSubmitting}
>
CANCEL
</button>
<button
className="cursor-pointer px-4 py-2 text-sm font-medium rounded-md bg-gradient-to-br from-[var(--primary)] to-blue-600 text-white hover:bg-[var(--modalSubmitBGHover)] transition-colors flex items-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed"
className="w-full sm:w-auto px-3 md:px-4 lg:px-6 py-2 md:py-3 text-xs md:text-sm font-medium rounded-md bg-gradient-to-br from-[var(--primary)] to-blue-600 text-white hover:opacity-90 hover:shadow-lg flex items-center justify-center gap-1 md:gap-2 disabled:opacity-60 disabled:cursor-not-allowed transition-all duration-200"
onClick={handleSubmit}
disabled={isSubmitting}
>
{isSubmitting ? (
<>
<FaSpinner className="animate-spin" />
{isEditMode ? 'UPDATING...' : 'CREATING...'}
<FaSpinner className="animate-spin w-3 h-3 md:w-4 md:h-4" />
<span>{isEditMode ? 'UPDATING...' : 'CREATING...'}</span>
</>
) : (
isEditMode ? 'UPDATE SIGNATURE' : 'CREATE SIGNATURE'
<span>{isEditMode ? 'UPDATE SIGNATURE' : 'CREATE SIGNATURE'}</span>
)}
</button>
</div>
</div>
</div>
</div>
);
};
export default AddSignatureModal;

View File

@ -224,20 +224,20 @@ const DrawSignatureCanvas: React.FC<Props> = ({ onSignatureChange, initialSignat
return (
<div className="h-full flex flex-col">
<div className="mb-6">
<h2 className="text-xl font-semibold text-gray-900 mb-2">Draw Signature</h2>
<p className="text-sm text-gray-600">Create your signature by drawing directly on the canvas</p>
<div className="mb-2 lg:mb-6">
<h2 className="text-lg sm:text-xl lg:text-2xl font-semibold text-gray-900 mb-1 sm:mb-2 ">Draw Signature</h2>
<p className="text-xs sm:text-sm text-gray-600 hidden sm:block">Create your signature by drawing directly on the canvas</p>
</div>
<div className="flex-1 flex flex-col">
<div className="grid grid-cols-12 gap-6 mb-2">
<div className="flex-1 overflow-y-auto">
<div className="grid grid-cols-1 lg:grid-cols-12 gap-4 lg:gap-6">
{/* Full Signature Canvas */}
<div className="col-span-8">
<label className="block text-sm font-medium text-gray-700 mb-2">Full Signature</label>
<div className="lg:col-span-8">
<label className="block text-xs sm:text-sm font-medium text-gray-700 mb-2">Full Signature</label>
<div className="border-2 border-dashed border-gray-300 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
<canvas
ref={canvasRef1}
className="w-full h-48 cursor-crosshair"
className="w-full h-51 cursor-crosshair"
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
@ -247,12 +247,12 @@ const DrawSignatureCanvas: React.FC<Props> = ({ onSignatureChange, initialSignat
</div>
{/* Initials Canvas */}
<div className="col-span-4">
<div className="lg:col-span-4">
<label className="block text-sm font-medium text-gray-700 mb-2">Initials</label>
<div className="border-2 border-dashed border-gray-300 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
<canvas
ref={canvasRef2}
className="w-full h-48 cursor-crosshair"
className="w-full h-51 cursor-crosshair"
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
@ -263,7 +263,7 @@ const DrawSignatureCanvas: React.FC<Props> = ({ onSignatureChange, initialSignat
</div>
{/* Controls */}
<div className="flex gap-4">
<div className="flex gap-4 mt-3">
<button
className="px-4 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
onClick={clearCanvas}

View File

@ -19,8 +19,8 @@ interface Signature {
signatureBlob: string;
signatureStampedBlob: string;
default: boolean;
signatureMimeType:string;
initialsMimeType:string
signatureMimeType: string;
initialsMimeType: string
}
const SignatureManager: React.FC = () => {
@ -30,11 +30,19 @@ const SignatureManager: React.FC = () => {
const [showAddSignature, setShowAddSignature] = useState<boolean>(false);
const [editingSignature, setEditingSignature] = useState<Signature | null>(null);
const signatureOptions = [
{ id: 1, name: 'print', initials: 'LA', style: 'print' },
{ id: 2, name: 'cursive', initials: 'LA', style: 'cursive' },
{ id: 3, name: 'script', initials: 'LA', style: 'script' },
{ id: 4, name: 'elegant', initials: 'LA', style: 'elegant' },
{ id: 5, name: 'modern', initials: 'LA', style: 'modern' },
{ id: 6, name: 'classic', initials: 'LA', style: 'classic' },
];
const getAllSignatures = async () => {
setLoading(true)
try {
let res = await api.get("/api/user/signatures")
console.log("getAllSignatures", res.data)
let signatureData = res?.data
setSignatures(signatureData)
} catch (error) {
@ -49,10 +57,8 @@ const SignatureManager: React.FC = () => {
}, [])
const handleEdit = (id: string) => {
console.log('Edit signature:', id);
let editSignature = signatures.find((item) => item.id === id);
console.log("editSignature", editSignature);
if (editSignature) {
setEditingSignature(editSignature);
setShowAddSignature(true);
@ -65,7 +71,7 @@ const SignatureManager: React.FC = () => {
setLoading(true)
try {
let res = await api.delete(`/api/user/signatures/${id}`)
console.log(res.data)
toast.success("Signature Delete Successfull", {
position: "top-center",
autoClose: 500,
@ -100,6 +106,32 @@ const SignatureManager: React.FC = () => {
setEditingSignature(null);
};
const renderSignatureText = (type, font, firstName, lastName, mode = 'name') => {
if (type !== 'SELECT') return null;
const selectedFont = signatureOptions.find(opt => opt.style === font);
const fontClass = `${selectedFont?.style || 'print'}`;
if (mode === 'initials') {
const initials = `${(firstName?.[0] ?? '')}${(lastName?.[0] ?? '')}`.toUpperCase();
return (
<div className={`text-center text-[24px]`} style={{fontFamily:selectedFont?.style}}>
{initials}
</div>
);
}
const fullName = `${firstName ?? ''} ${lastName ?? ''}`.trim();
return (
<div className={`text-center text-[20px]`}style={{fontFamily:selectedFont?.style}}>
<div>{fullName}</div>
</div>
);
};
return (
<>
{loading ? <div className=' flex items-center justify-center'>
@ -111,7 +143,7 @@ const SignatureManager: React.FC = () => {
</div>
</div> :
<div className="min-h-screen bg-white p-3 rounded-md px-4 mb-6">
<div className="max-w-[84vw] mx-auto">
<div className="max-w-[84vw] mx-auto ">
<>
{/* Header */}
<div className="flex items-center justify-between mb-3">
@ -126,107 +158,121 @@ const SignatureManager: React.FC = () => {
</div>
{/* Table Card */}
<div className="bg-white rounded-md overflow-hidden border border-gray-100">
{/* Table Header */}
<div className="bg-gray-50 border-b border-gray-200">
<div className="grid grid-cols-12 gap-4 px-6 py-4">
<div className="col-span-5">
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wider">Signature</h3>
</div>
<div className="col-span-5">
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wider">Initial</h3>
</div>
<div className="col-span-2">
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wider text-right">Actions</h3>
<div className="overflow-x-auto">
<div className="bg-white rounded-md min-w-[800px] md:min-w-full overflow-hidden border border-gray-100">
{/* Table Header */}
<div className="bg-gray-50 border-b border-gray-200 ">
<div className="grid grid-cols-12 gap-4 px-6 py-4">
<div className="col-span-5">
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wider">Signature</h3>
</div>
<div className="col-span-5">
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wider">Initial</h3>
</div>
<div className="col-span-2">
<h3 className="text-sm font-semibold text-gray-700 uppercase tracking-wider text-right">Actions</h3>
</div>
</div>
</div>
</div>
{/* Table Body */}
<div className="divide-y divide-gray-100">
{signatures.map((signature, index) => (
<div key={signature.id} className="grid grid-cols-12 gap-4 px-6 py-9 hover:bg-gray-50 transition-colors duration-150">
{/* Signature Column */}
<div className="col-span-5">
<div className="flex flex-col space-y-2 relative ps-6 border-l-3 border-blue-600 rounded-bl-2xl rounded-tl-2xl">
{/* Label */}
<div className="text-sm text-gray-600 font-medium mb-1">
Signed by:
</div>
{/* Signature Image */}
<div className="bg-white rounded-lg p-1 flex items-center justify-center ">
<img
src={`data:${signature.signatureMimeType};base64,${signature.signatureBlob}`}
className="h-[50px] w-[250px] object-contain"
alt="Signature"
/>
</div>
{/* Signature ID */}
<div className="text-xs text-gray-500 truncate">
{signature.signatureHash}
</div>
</div>
</div>
{/* Initial Column */}
<div className="col-span-5">
<div className="flex flex-col space-y-2 relative ps-6 border-l-3 border-green-600 rounded-bl-2xl rounded-tl-2xl">
{/* Label */}
<div className="text-sm text-gray-600 font-medium mb-1">
Initials
</div>
{/* Signature Image */}
<div className="bg-white rounded-lg p-1 flex items-center justify-center ">
<img
src={`data:${signature.initialsMimeType};base64,${signature.initialsBlob}`}
className="h-[50px] object-contain"
alt="DS Signature"
/>
</div>
{/* Initial ID */}
<div className="text-xs text-gray-500 truncate">
{signature.initialsHash}
</div>
</div>
</div>
{/* Actions Column */}
<div className="col-span-2 flex justify-between items-start pt-9 ps-8 ">
<div className="relative ">
<button
onClick={() => toggleDropdown(signature.id)}
className="bg-gray-100 hover:bg-gray-200 text-gray-700 px-1.5 py-1.5 text-[13px] rounded-lg font-semibold flex items-center transition-all duration-200 border border-gray-300 "
>
ACTIONS
<FiMoreVertical />
</button>
{/* Dropdown Menu */}
{activeDropdown === signature.id && (
<div className="absolute right-0 mt-0.5 w-28 bg-white rounded-lg border border-gray-200 z-10 py-1">
<button
onClick={() => handleEdit(signature.id)}
className="w-full px-4 py-1 text-left text-gray-500 hover:bg-blue-50 hover:text-blue-700 flex items-center gap-3 text-sm transition-colors duration-150"
>
<FiEdit3 />
Edit
</button>
<button
onClick={() => handleDelete(signature.id)}
className="w-full px-4 py-1 text-left text-gray-500 hover:bg-red-50 hover:text-red-700 flex items-center gap-3 text-sm transition-colors duration-150"
>
<FiTrash2 />
Delete
</button>
{/* Table Body */}
<div className="divide-y divide-gray-100">
{signatures.map((signature, index) => (
<div key={signature.id} className="grid grid-cols-12 gap-4 px-6 py-9 hover:bg-gray-50 transition-colors duration-150">
{/* Signature Column */}
<div className="col-span-5">
<div className="flex flex-col space-y-2 relative ps-6 border-l-3 border-blue-600 rounded-bl-2xl rounded-tl-2xl">
{/* Label */}
<div className="text-sm text-gray-600 font-medium mb-1">
Signed by:
</div>
)}
{/* Signature Image or Name/Initials */}
<div className="bg-white rounded-lg p-1 flex items-center justify-center">
{signature?.signatureType !== 'SELECT' ? (
<img
src={`data:${signature?.signatureMimeType};base64,${signature?.signatureBlob}`}
className="h-[50px] w-[250px] object-contain"
alt="Signature"
/>
) : (
renderSignatureText(signature?.signatureType, signature?.font, signature?.firstName, signature?.lastName, 'name')
)}
</div>
{/* Signature ID */}
<div className="text-xs text-gray-500 truncate">
{signature.signatureHash}
</div>
</div>
</div>
{/* Initial Column */}
<div className="col-span-5">
<div className="flex flex-col space-y-2 relative ps-6 border-l-3 border-green-600 rounded-bl-2xl rounded-tl-2xl">
{/* Label */}
<div className="text-sm text-gray-600 font-medium mb-1">
Initials
</div>
{/* Signature Initials: Image or Generated Text */}
<div className="bg-white rounded-lg p-1 flex items-center justify-center">
{signature?.signatureType !== 'SELECT' ? (
<img
src={`data:${signature.initialsMimeType};base64,${signature.initialsBlob}`}
className="h-[50px] object-contain"
alt="Initials"
/>
) : (
renderSignatureText(signature?.signatureType, signature?.font, signature?.firstName, signature?.lastName, 'initials')
)}
</div>
{/* Initial ID */}
<div className="text-xs text-gray-500 truncate">
{signature.initialsHash}
</div>
</div>
</div>
{/* Actions Column */}
<div className="col-span-2 flex justify-between items-start pt-9 ps-8 ">
<div className="relative ">
<button
onClick={() => toggleDropdown(signature.id)}
className="bg-gray-100 hover:bg-gray-200 text-gray-700 px-1.5 py-1.5 text-[13px] rounded-lg font-semibold flex items-center transition-all duration-200 border border-gray-300 "
>
ACTIONS
<FiMoreVertical />
</button>
{/* Dropdown Menu */}
{activeDropdown === signature.id && (
<div className={`absolute right-0 mt-0.5 -top-5 w-28 bg-white rounded-lg border border-gray-200 z-10 py-1`}>
<button
onClick={() => handleEdit(signature.id)}
className="w-full px-4 py-1 text-left text-gray-500 hover:bg-blue-50 hover:text-blue-700 flex items-center gap-3 text-sm transition-colors duration-150"
>
<FiEdit3 />
Edit
</button>
<button
onClick={() => handleDelete(signature.id)}
className="w-full px-4 py-1 text-left text-gray-500 hover:bg-red-50 hover:text-red-700 flex items-center gap-3 text-sm transition-colors duration-150"
>
<FiTrash2 />
Delete
</button>
</div>
)}
</div>
</div>
</div>
</div>
))}
))}
</div>
</div>
</div>
@ -252,8 +298,8 @@ const SignatureManager: React.FC = () => {
)}
{showAddSignature && (
<AddSignatureModal
setShowAddSignature={handleModalClose}
<AddSignatureModal
setShowAddSignature={handleModalClose}
getAllSignatures={getAllSignatures}
editingSignature={editingSignature}
/>

View File

@ -1,62 +1,57 @@
import { FiX, FiEdit2 } from 'react-icons/fi';
import { FiX, FiEdit2 } from "react-icons/fi";
interface Account {
id: number;
isDefault: boolean;
name: string;
id: number;
isDefault: boolean;
name: string;
}
interface UserData {
id: number;
name:string
email: string;
language: string;
account: Account;
id: number;
name: string;
email: string;
language: string;
account: Account;
}
interface UserProfileProps {
userData: UserData;
userData: UserData;
}
const UserProfile: React.FC<UserProfileProps> = ({ userData }) => {
const getInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
};
return (
<div className="bg-white rounded-md shadow-sm flex w-full p-6">
{/* Profile Picture */}
<div className="flex-shrink-0 text-center">
<div className="w-20 h-20 bg-[var(--primary)] text-white font-bold text-2xl rounded-full flex items-center justify-center shadow-lg">
{userData.name.slice(0,2).toUpperCase()}
</div>
</div>
return (
<div className="bg-white rounded-md shadow-sm flex flex-col sm:flex-row items-center sm:items-start w-full p-6 gap-6">
{/* Profile Picture */}
<div className="flex-shrink-0 text-center">
<div className="w-20 h-20 bg-gradient-to-br from-[var(--primary)] to-blue-600 text-white font-bold text-2xl rounded-full flex items-center justify-center shadow-lg">
{userData.name.slice(0, 2).toUpperCase()}
</div>
</div>
{/* Info Fields */}
<div className="flex flex-col justify-center flex-1 ms-10">
{/* Row: Name */}
<div className="flex py-1">
<div className="text-gray-500 font-medium text-[13px] w-32">Name</div>
<div className="text-gray-400 font-medium text-[13px]">
{userData.name}
</div>
</div>
{/* Row: Email */}
<div className="flex py-1">
<div className="text-gray-500 font-medium text-[13px] w-32">Email</div>
<div className="text-gray-400 font-medium text-[13px]">{userData.email}</div>
</div>
{/* Row: Account Name */}
<div className="flex py-1">
<div className="text-gray-500 font-medium text-[13px] w-32">Account name</div>
<div className="text-gray-400 font-medium text-[13px]">
{userData.account.name}
</div>
</div>
</div>
{/* Info Fields */}
<div className="flex flex-col justify-center flex-1 w-full">
{/* Row: Name */}
<div className="flex flex-col sm:flex-row py-1">
<div className="text-gray-500 font-medium text-[13px] sm:w-32">Name</div>
<div className="text-gray-400 font-medium text-[13px]">{userData.name}</div>
</div>
{/* Row: Email */}
<div className="flex flex-col sm:flex-row py-1">
<div className="text-gray-500 font-medium text-[13px] sm:w-32">Email</div>
<div className="text-gray-400 font-medium text-[13px]">{userData.email}</div>
</div>
);
{/* Row: Account Name */}
<div className="flex flex-col sm:flex-row py-1">
<div className="text-gray-500 font-medium text-[13px] sm:w-32">Account name</div>
<div className="text-gray-400 font-medium text-[13px]">
{userData.account.name}
</div>
</div>
</div>
</div>
);
};
export default UserProfile
export default UserProfile;

View File

@ -87,7 +87,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
signTagId
}) => {
console.log("savedModal", recipient)
const [activeTab, setActiveTab] = useState<'TYPED' | 'DRAW' | 'UPLOAD' | 'SAVED'>('TYPED');
const [fullName, setFullName] = useState('');
const [initials, setInitials] = useState('');
@ -120,8 +119,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
},
});
console.log("User data", user)
const [selectedSignature, setSelectedSignature] = useState<SelectStyle>(
signatureOptions.length > 0 ? { id: signatureOptions[0].id, style: signatureOptions[0].style } : { id: 0, style: "" }
);
@ -172,7 +169,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
signature: signatureBlob,
initial: initialsBlob,
});
console.log("saved Called Line 174")
}
}
setPreSaveSignatures(preSavedSignatures)
@ -223,7 +219,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
const handleSubmit = async () => {
setIsSubmitting(true);
console.log("handleSubmit Called")
if (!signatures.fullSignature || !signatures.initials) {
alert('Please provide both signature and initials');
setIsSubmitting(false);
@ -243,7 +238,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
font: selectedSignature.style
};
console.log("payload", payload)
// if (isEditMode && editingSignature) {
// // Update existing signature
// const updatePayload = {
@ -273,7 +267,6 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
"ngrok-skip-browser-warning": "69420"
}
});
console.log("handleSubmit", res);
toast.success("Signature Created Successfully", {
position: "top-center",
@ -532,7 +525,7 @@ const AddSignatureModal: React.FC<AddSignatureModalProps> = ({
// let currUser = res?.data;
setUser(recipient);
setFullName(recipient.firstName + " " + recipient.lastName);
setInitials(recipient.firstName.slice(0, 1) + recipient.lastName.slice(0, 1));
setInitials((recipient.firstName.slice(0, 1) + recipient.lastName.slice(0, 1)).toUpperCase());
} catch (error) {
console.error("Error fetching user details:", error);
}

View File

@ -13,7 +13,6 @@ interface InitialConProps {
const InitialCon: React.FC<InitialConProps> = ({ openInitial, setOpenInitial, savedInitial, setSavedInitial }) => {
const handleSaveInitial = (signatureDataUrl: string) => {
console.log(signatureDataUrl, "savedInitial ------ 123");
setSavedInitial(signatureDataUrl);
setOpenInitial(false)

View File

@ -14,7 +14,6 @@ interface SignatureConProps {
const SignatureCon: React.FC<SignatureConProps> = ({ recipientId, openSign, setOpenSign, savedSignature, setSavedSignature }) => {
const handleSaveSignature = (signatureDataUrl: string) => {
console.log('Signature saved:', signatureDataUrl);
axios.post(`${import.meta.env.VITE_BASE_URI}/api/sign/signature?recipientId=${recipientId}`,
{
signature: signatureDataUrl,
@ -23,9 +22,7 @@ const SignatureCon: React.FC<SignatureConProps> = ({ recipientId, openSign, setO
},
{ headers: { "ngrok-skip-browser-warning": "69420", } })
.then((res) => {
console.log(res, "Signature saved response")
if (res.status === 200 || res.status === 201) {
console.log('Signature saved successfully');
setSavedSignature(signatureDataUrl);
setOpenSign(false)
}

View File

@ -9,9 +9,6 @@ interface StampUploadType {
const StampUpload: React.FC<StampUploadType> = ({ stamp, setStamp }) => {
console.log(stamp, "stamp upload component");
// const [preview, setStamp] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
@ -23,7 +20,6 @@ const StampUpload: React.FC<StampUploadType> = ({ stamp, setStamp }) => {
reader.onload = () => {
if (typeof reader.result === 'string') {
console.log(reader.result, "reader result");
setStamp((prev) => {
return (
{

View File

@ -41,6 +41,34 @@ const TemplateTable = () => {
}, [activeAccountId])
// Listen for sessionStorage changes
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === 'activeAccountId') {
const newActiveAccountId = e.newValue ? JSON.parse(e.newValue) : null;
setActiveAccountId(newActiveAccountId);
}
};
// Listen for storage events (works for changes from other tabs)
window.addEventListener('storage', handleStorageChange);
// Custom event listener for same-tab changes
const handleCustomStorageChange = (e: CustomEvent) => {
if (e.detail.key === 'activeAccountId') {
setActiveAccountId(e.detail.newValue);
}
};
window.addEventListener('sessionStorageChange', handleCustomStorageChange as EventListener);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('sessionStorageChange', handleCustomStorageChange as EventListener);
};
}, []);
const formatDate = (timestamp: number) => {
return new Date(timestamp * 1000).toLocaleString();
};
@ -60,7 +88,7 @@ const TemplateTable = () => {
templateId: item.id,
};
let res = await api.post(`/api/accounts/${activeAccountId}/transactions`, payload)
console.log("handleUseClick", res.data)
// /process-step-one/:accountId/:transactionId
navigate(`/process-step-one/${activeAccountId}/${res?.data?.id}?useTemplate=true`);
} catch (error) {
@ -192,7 +220,6 @@ const TemplateTable = () => {
<button
onMouseDown={() => {
setShowMenu(null);
console.log('Delete clicked', item);
}}
className="block w-full text-left px-4 py-2 text-sm hover:bg-gray-100 text-red-600"
>

View File

@ -28,8 +28,9 @@ const Templates = () => {
const filters = ["All", "My Templates", "Shared"];
const handleAddTemplate = async () => {
console.log("handleAddTemplate called");
try {
const res = await api.post(`/api/accounts/${activeAccountId}/templates`);
navigate(`/process-step-one/${activeAccountId}/template/${res.data.id}`)
@ -39,23 +40,23 @@ const Templates = () => {
}
return (
<div className="p-3 text-sm">
{/* Header */}
<div className="flex items-center justify-between mb-3">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
{/* Filter as pill buttons */}
<div className="flex gap-2">
<div className="flex flex-wrap gap-2">
{filters.map((filter) => (
<button
key={filter}
onClick={() => setActiveFilter(filter)}
className={`px-3 py-1 rounded-full text-xs border transition
${activeFilter === filter
className={`px-3 py-1 rounded-full text-xs border transition
${activeFilter === filter
? "bg-[var(--primary)] text-white"
: "border-gray-300 text-gray-600 hover:bg-gray-100"
}`}
@ -65,20 +66,22 @@ const Templates = () => {
))}
</div>
{/* Add Template Button */}
<div
onClick={handleAddTemplate}
className="flex items-center gap-1 bg-gradient-to-br from-[var(--primary)] to-blue-600 px-2.5 py-1.5 rounded-sm cursor-pointer hover:opacity-90">
<IoMdAdd className="text-white" />
<button
className="text-white rounded text-sm hover:opacity-90">
className="flex items-center justify-center gap-1 bg-gradient-to-br from-[var(--primary)] to-blue-600 px-3 py-2 rounded-sm cursor-pointer hover:opacity-90"
>
<IoMdAdd className="text-white text-lg" />
<button className="text-white text-sm font-medium">
Add Template
</button>
</div>
</div>
{/* Table */}
<section className="my-4 mx-3"></section>
<TemplateTable/>
<TemplateTable />
</div>
);
};

View File

@ -50,6 +50,7 @@ const AuditModal: React.FC<AuditModalProps> = ({ closeModal }) => {
setLoading(true)
try {
let res = await api.get(`/api/accounts/${accountId}/transactions/${transactionId}/audit?lang=${userDetails.language || ''}`)
// let res = await api.get(`/api/accounts/${accountId}/transactions/${transactionId}/audit?lang=hi`)
if (res?.status === 200) {
// console.log(res?.data?.events)
let auditResponse = res?.data?.events
@ -125,11 +126,12 @@ const AuditModal: React.FC<AuditModalProps> = ({ closeModal }) => {
];
const getActionIcon = (action: string) => {
const icons = {
'CREATED': <FiFileText className="w-4 h-4 text-sky-500" />,
'SENT': <FiSend className="w-4 h-4" />,
'INVITED': <FiMail className="w-4 h-4" />,
'COMPLETED': <FiCheckCircle className="w-4 h-4" />,
'COMPLETED': <FiCheckCircle className="w-4 h-4 bg-green-600 text-white rounded-full" />,
'RE_SENT_INVITATION': <FiRefreshCw className="w-4 h-4" />,
'RE_SENT_EXPIRED_INVITATION': <FiRefreshCw className="w-4 h-4" />,
'VIEWED': <FiEye className="w-4 h-4" />,
@ -147,7 +149,6 @@ const AuditModal: React.FC<AuditModalProps> = ({ closeModal }) => {
'REASSIGNED': <FiUserPlus className="w-4 h-4" />,
'EDITED': <FiEdit className="w-4 h-4" />,
};
return icons[action as keyof typeof icons] || <FiActivity className="w-4 h-4" />;
};
@ -217,15 +218,12 @@ const AuditModal: React.FC<AuditModalProps> = ({ closeModal }) => {
};
return (
<div className="fixed inset-0 flex items-center justify-center backdrop-blur-sm bg-white/10 z-50">
<div className="bg-white rounded-md shadow-md w-full max-w-[75vw] max-h-[95vh] min-h-[85vh] flex flex-col">
<div className="fixed inset-0 flex items-center justify-center backdrop-blur-sm bg-white/10 z-50 px-2">
<div className="bg-white rounded-md shadow-md w-full h-[90vh] max-w-[95vw] sm:max-w-[90vw] md:max-w-[85vw] lg:max-w-[75vw] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-3 border-b border-gray-200 bg-[var(--primary)] rounded-t-md">
<div className="flex items-center">
<h2 className="text-xl font-semibold text-white">
Audit Status
</h2>
</div>
<h2 className="text-base sm:text-lg md:text-xl font-semibold text-white">Audit Status</h2>
<button
onClick={closeModal}
className="text-white cursor-pointer transition-colors hover:text-gray-200"
@ -236,74 +234,57 @@ const AuditModal: React.FC<AuditModalProps> = ({ closeModal }) => {
{/* Content */}
<div className="flex-1 overflow-y-auto p-4 no-scrollbar">
{/* {loading ? <LoaderUi /> : ""} */}
{auditStatus.length ?
<div className="space-y-1.5">
{/* <div className="text-sm text-gray-500 font-medium mb-2">TODAY</div> */}
{auditStatus.length ? (
<div className="space-y-3">
{auditStatus.map((item, index) => (
<div key={index} className="flex items-start space-x-4 pb-3 border-b border-gray-100 last:border-b-0">
<div className={`${getActionColor(item.action)} mt-1`}>
{getActionIcon(item.action)}
<div key={index} className="flex items-start space-x-3 pb-3 border-b border-gray-100 last:border-b-0">
<div className={`${getActionColor(item.action.toUpperCase())} mt-1`}>
{getActionIcon(item.action.toUpperCase())}
</div>
<div className="flex-1">
<p className="text-gray-600 font-medium text-sm mb-1">{item.message}</p>
<div className="flex items-center space-x-2 text-xs text-gray-600 mb-1">
<p className="text-gray-600 font-medium text-xs sm:text-xs mb-1">
{item.message}
</p>
<div className="flex flex-wrap items-center space-x-2 text-xs text-gray-600 mb-1">
<span>Action: {item.action}</span>
{extractEmailFromMessage(item.message) && (
<>
<span>•</span>
<span className="text-blue-600">{extractEmailFromMessage(item.message)}</span>
<span className="hidden sm:inline">•</span>
<span className="text-blue-600">
{extractEmailFromMessage(item.message)}
</span>
</>
)}
</div>
<div className="flex items-center space-x-2 mb-2">
<span className="text-xs text-gray-600">Status:</span> <span className={`px-2 py-0.5 text-xs rounded-full ${getStatusBadge(item.status)}`}>
<div className="flex flex-wrap items-center space-x-2 mb-2 text-xs text-gray-600">
<span>Status:</span>
<span className={`px-2 py-0.5 rounded-full ${getStatusBadge(item.status)}`}>
{item.status}
</span>
<span className="text-xs text-gray-500">{formatTimestamp(item.timestamp)}</span>
<span className="text-gray-500">{formatTimestamp(item.timestamp)}</span>
{item.language && (
<span className="text-xs text-gray-400 uppercase">{item.language}</span>
<span className="text-gray-400 uppercase">{item.language}</span>
)}
</div>
{/* Event Data Details */}
{/* <div className="grid grid-cols-2 gap-4 text-xs text-gray-600 bg-gray-50 p-2 rounded">
{item.eventData.ip && (
<div>
<span className="font-medium text-gray-700">IP:</span> {item.eventData.ip}
</div>
)}
{item.eventData.timezone && (
<div>
<span className="font-medium text-gray-700">Timezone:</span> {item.eventData.timezone}
</div>
)}
{item.eventData.latitude && item.eventData.longitude && (
<div className="col-span-2">
<span className="font-medium text-gray-700">Location:</span>
<span className="ml-1">Lat: {item.eventData.latitude}, Lng: {item.eventData.longitude}</span>
</div>
)}
</div> */}
</div>
</div>
))}
</div> :
<div className="flex justify-center items-center">
</div>
) : (
<div className="flex justify-center items-center h-full">
<img
src={logoRecord}
alt="Record Not Found"
className="w-80 h-80 opacity-70" // adjust size and appearance
className="w-64 h-64 opacity-70 object-contain"
/>
</div>
}
)}
</div>
{/* Footer */}
<div className="flex justify-between items-center p-3 border-t border-gray-200 bg-gray-50">
<div className="text-sm text-gray-600">
<div className="flex justify-between items-center p-3 border-t border-gray-200 bg-gray-50 text-sm">
<div className="text-gray-600">
Showing {auditStatus.length} event{auditStatus.length !== 1 ? 's' : ''}
</div>
<button
@ -315,6 +296,7 @@ const AuditModal: React.FC<AuditModalProps> = ({ closeModal }) => {
</div>
</div>
</div>
);
};

View File

@ -77,8 +77,6 @@ const TransactionView = () => {
setIsModalOpen(false); // update state immediately
};
console.log(transactionDetails, "line 37");
const fetchData = async () => {
try {
const [res1, res2] = await Promise.all([api.get(`/api/accounts/${accountId}/transactions/${transactionId}`),
@ -91,7 +89,7 @@ const TransactionView = () => {
const fetchDocuments = async () => {
try {
const res = await api.get(`https://concrete-gladly-mullet.ngrok-free.app/api/accounts/${accountId}/transactions/${transactionId}/documents?include_images=true`)
const res = await api.get(`/api/accounts/${accountId}/transactions/${transactionId}/documents`)
if (res?.status === 200) {
let resDoc = res?.data
setDocumentsData(resDoc)
@ -112,15 +110,27 @@ const TransactionView = () => {
window.open(`./../../../../sign/${id}/${SignTypeEnum.selfSign}`)
}
const getStatusBadge = (status: string) => {
const statusClasses = {
'SENT': 'bg-blue-100 text-blue-800',
'COMPLETED': 'bg-green-100 text-green-800',
'FAILED': 'bg-red-100 text-red-800',
'PENDING': 'bg-yellow-100 text-yellow-800',
'VIEWED': 'bg-purple-100 text-purple-800',
'REJECTED': 'bg-red-100 text-red-800'
};
return statusClasses[status as keyof typeof statusClasses] || 'bg-gray-100 text-gray-800';
};
return (
<>
{transactionDetails &&
<>
<div className='mt-2 flex justify-center items-stretch max-w-90vw min-h-[88vh] h-full bg-white rounded-lg shadow-sm mx-3'>
<div className="w-full px-6 py-4 rounded-tl-sm text-xs border-r-2 border-gray-200 overflow-y-auto">
<div className='mt-2 grid grid-cols-1 lg:grid-cols-12 items-stretch max-w-90vw min-h-[88vh] h-full bg-white rounded-lg shadow-sm mx-3'>
<div className="lg:col-span-10 w-full px-6 py-4 rounded-tl-sm text-xs border-r-2 border-gray-200 overflow-y-auto">
{/* Header */}
<h1 className='text-lg font-semibold text-gray-800'>
Complete with Forms Made Easy: <span className='text-slate-600'>{transactionDetails?.transaction?.subject ?? "Untitled"}</span>
Complete with Sign Made Easy: <span className='text-slate-600'>{transactionDetails?.transaction?.subject ?? "Untitled"}</span>
</h1>
<div className='mt-2'>
@ -170,38 +180,55 @@ const TransactionView = () => {
{/* Recipients List */}
{transactionDetails.recipients.map((recipient, index) => (
<div key={index}>
<div className='mt-2 flex justify-between items-center'>
<div className='flex gap-8 items-center'>
{/* <p className='text-slate-600'>{index+1}</p> */}
<div className="mt-2 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3 sm:gap-0 ">
{/* Left section: recipient info */}
<div className="flex flex-col sm:flex-row gap-4 sm:items-center">
<div>
<p className='text-slate-600 font-semibold'>{recipient.name}</p>
<p className='text-slate-600'>{recipient.email}</p>
{recipient.hostEmail !== null && recipient.hostEmail !== "" && <p className='text-xs'><i><b>Host: {recipient.hostEmail}</b></i></p>}
<p className="text-slate-600 font-semibold text-xs sm:xs">{recipient.name}</p>
<p className="text-slate-600 text-xs sm:text-xs">{recipient.email}</p>
{recipient.hostEmail && (
<p className="text-xs text-gray-500 italic">
<strong>Host:</strong> {recipient.hostEmail}
</p>
)}
</div>
</div>
<div className='flex flex-col leading-4.5 items-start text-md text-slate-600'>
<div className='flex gap-3 items-center relative'>
<div className='flex gap-1 items-center relative'>
<AiFillSignature className='absolute left-[-30px] text-[1rem]' />
<p className='text-black font-semibold'>{recipient.status}</p>
{/* Right section: status and actions */}
<div className="flex flex-col items-start sm:items-end gap-1 text-sm text-slate-600">
<div className="flex flex-wrap gap-3 items-center relative">
<div className="pl-6 relative">
<AiFillSignature className="absolute left-0 top-0 text-[1rem]" />
<p className={`text-black text-xs font-semibold rounded-lg px-2 py-0.5 ${getStatusBadge(recipient.status)}`}>{recipient.status}</p>
</div>
{recipient.email === user.email && recipient.status !== "COMPLETED" &&
<p
{recipient.email === user.email && recipient.status !== "COMPLETED" && (
<button
onClick={() => handleNavigateToSign(recipient.id)}
className='text-white rounded-sm bg-[var(--primary)] px-3 py-1 font-semibold cursor-pointer'>
className="text-white rounded-sm bg-[var(--primary)] px-3 py-1 font-semibold text-xs hover:bg-opacity-90 transition"
>
Sign
</p>}
</button>
)}
</div>
{recipient.status !== "PENDING" && <p>on {recipient.completedAt}</p>}
{/* <a href={recipient.viewLink} className='text-blue-600 hover:underline'>
View signed location
</a> */}
{recipient.status !== "PENDING" && (
<p className="text-xs text-gray-500">on {recipient.completedAt}</p>
)}
{/* Optional signed document link */}
{/* {recipient.viewLink && (
<a href={recipient.viewLink} className="text-blue-600 text-xs hover:underline">
View signed location
</a>
)} */}
</div>
</div>
<hr className='my-2 border-slate-200' />
<hr className="my-3 border-slate-200" />
</div>
))}
</div>
}
@ -219,19 +246,25 @@ const TransactionView = () => {
</div>}
</div>
<div className='lg:w-[15vw] sm:w-[20vw] text-xs rounded-sm max-h-[88vh] overflow-y-auto no-scrollbar'>
<div className='lg:col-span-2 text-xs rounded-sm max-h-[88vh] overflow-y-auto no-scrollbar'>
{documentsData.map((docsD, index) => (
<div className='p-4 flex flex-col gap-2 cursor-pointer' key={docsD.id}>
<p>{docsD.name}</p>
<div className='border-3 rounded-sm border-slate-300 relative text-xs'>
{docsD?.pages[0]?.src ?
<img style={{ width: "200px", height: "160px" }} src={docsD?.pages[0]?.src} alt="" loading='lazy'/>
:
<FaFile className='h-35 w-20 mx-5 text-gray-300' />}
{docsD?.thumbnail ? (
<img
style={{ width: "200px", height: "160px" }}
src={`data:image/jpeg;base64,${docsD.thumbnail}`} // Adjust MIME type if needed
alt=""
loading="lazy"
/>
) : (
<FaFile className="h-35 w-20 mx-5 text-gray-300" />
)}
<div className='bg-slate-100 p-2 absolute w-full bottom-[0px]'>
<p className='text-[0.7rem] text-slate-500 flex justify-between items-center'>
<span> 1 of {docsD?.pages?.length}</span>
<span className='cursor-pointer'><Link to={`/process-step-two/${accountId}/${transactionId}`}><MdEditDocument size={16} /></Link></span>
<p className='text-[0.7rem] text-slate-500 flex justify-end items-center'>
{/* <span> 1 of {docsD?.pages?.length}</span> */}
<span className='cursor-pointer '><Link to={`/process-step-two/${accountId}/${transactionId}`}><MdEditDocument size={16} /></Link></span>
</p>
</div>

View File

@ -43,18 +43,14 @@ const DocView = () => {
function zoom(percentage: number, contentClass: string) {
console.log("calling zoom function", percentage, contentClass);
const content = document.querySelector(`.${contentClass}`);
const scale = percentage // 100;
if(content) {
console.log("calling zoom function Printing Content", content);
content.style.transform = `scale(${scale})`;
}
}
useEffect(() => {
console.log("Calling useEffect for zoom", fitObj[selFitIndx].value);
let indx = fitObj[selFitIndx].value
if (indx === "FIT") {
indx = "100";
@ -62,8 +58,6 @@ const DocView = () => {
zoom(Number(indx), 'zoom-con')
}, [selFitIndx])
console.log(isFitDd);
return (
<>

View File

@ -19,8 +19,6 @@ export const createAxiosInstance = () => {
const user = JSON.parse(parsedRoot.user);
const accessToken = user.accessToken;
console.log(accessToken, "accessToken");
return axios.create({
baseURL: import.meta.env.VITE_BASE_URI,
withCredentials: true,

View File

@ -59,6 +59,18 @@
}
.btn {
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
/* Button press effect */
.btn:active {
transform: scale(0.97) translateY(1px);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) inset;
}
/* Sortable CSS */
.sortable-ghost {

View File

@ -1,166 +1,3 @@
// import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
// // import { v4 as uuidv4 } from "uuid";
// import { hideLoader, showLoader } from "./loaderSlice";
// // import { showModal } from "./modalSlice";
// // import { updateSelectedDocuments } from "./selectedDocsSlice";
// import api from "../../config/api";
// import { Bounce, toast } from "react-toastify";
// // import { createAxiosInstance } from "../../config/axiosInstance";
// // const axiosInstance = createAxiosInstance();
// export interface Document {
// id: string;
// name: string;
// extension: string;
// original?: boolean;
// corrupted?: boolean;
// isCompleted: boolean;
// status: string;
// }
// export interface DocumentState {
// documents: Document[];
// loading: boolean;
// error: string | null;
// }
// const initialState: DocumentState = {
// documents: [],
// loading: false,
// error: null,
// };
// interface uploadArgs {
// formData: FormData;
// accountId: string;
// transactionId: string;
// }
// // Fetch documents from API
// export const fetchDocuments = createAsyncThunk<Document[], { accountId: string, transactionId: string }>(
// "documents/fetchDocuments",
// async ({ accountId, transactionId }, { rejectWithValue }) => {
// try {
// const response = await api.get(`/api/accounts/${accountId}/transactions/${transactionId}/documents?include_images=true`);
// return response.data as Document[];
// } catch (error: any) {
// // if(error.status === 401) {}
// return rejectWithValue(error.response?.data || "Failed to fetch documents");
// }
// }
// );
// // Upload multiple documents using FormData (Key: "document")
// export const uploadDocuments = createAsyncThunk<Document[], uploadArgs>(
// "documents/uploadDocuments",
// async ({ formData, accountId, transactionId }, { dispatch, rejectWithValue }) => {
// try {
// dispatch(showLoader("Uploading documents..."));
// console.log("Form Data", formData.getAll("document"))
// const response = await api.post(`/api/accounts/${accountId}/transactions/${transactionId}/documents`, formData, {
// headers: {
// "Content-Type": "multipart/form-data"
// },
// });
// console.log("Form Uploaded Response DocumentSlice Line 185", response.data)
// dispatch(hideLoader());
// return [response.data];
// } catch (error: any) {
// dispatch(hideLoader());
// toast.error("Error Uploading Document", {
// position: "bottom-right",
// autoClose: 3000,
// hideProgressBar: false,
// closeOnClick: false,
// pauseOnHover: false,
// draggable: false,
// progress: undefined,
// theme: "light",
// transition: Bounce,
// });
// console.log("Failed Uploading Documents")
// throw new Error("Failed Uploading Documents")
// // Mock data in case of failure
// // const failedDocuments = formData.getAll("document").map((file: any) => ({
// // id: uuidv4(),
// // name: file.name,
// // extension: file.name.split(".").pop() || "unknown",
// // original: Math.random() < 0.5,
// // corrupted: Math.random() < 0.5,
// // }));
// // dispatch(updateSelectedDocuments({ documents: failedDocuments }));
// // return failedDocuments; // Instead of rejecting, return mock data
// }
// }
// );
// const documentSlice = createSlice({
// name: "documents",
// initialState,
// reducers: {
// setDocuments: (state, action: PayloadAction<Document[]>) => {
// state.documents = action.payload;
// },
// setDocProgComplete: (state, action: PayloadAction<string>) => {
// const docIndex = state.documents.findIndex(doc => doc.id === action.payload);
// if (docIndex !== -1) {
// state.documents[docIndex].isCompleted = true;
// }
// },
// resetDocuments: (state) => {
// state.documents = [];
// },
// deleteDocument: (state, action: PayloadAction<string>) => {
// state.documents = state.documents.filter(doc => doc.id !== action.payload);
// },
// },
// extraReducers: (builder) => {
// builder
// // Fetch documents
// .addCase(fetchDocuments.pending, (state) => {
// state.loading = true;
// state.error = null;
// })
// .addCase(fetchDocuments.fulfilled, (state, action: PayloadAction<Document[]>) => {
// state.loading = false;
// state.documents = action.payload;
// })
// .addCase(fetchDocuments.rejected, (state, action) => {
// state.loading = false;
// state.error = action.payload as string;
// })
// // Upload multiple documents
// .addCase(uploadDocuments.pending, (state) => {
// state.loading = true;
// state.error = null;
// })
// .addCase(uploadDocuments.fulfilled, (state, action: PayloadAction<Document[]>) => {
// state.loading = false;
// state.documents = [...action.payload, ...state.documents];
// })
// .addCase(uploadDocuments.rejected, (state, action) => {
// state.loading = false;
// state.error = action.payload as string;
// });
// },
// });
// export const { resetDocuments, setDocuments, setDocProgComplete, deleteDocument } = documentSlice.actions;
// export default documentSlice.reducer;
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { toast, Bounce } from 'react-toastify';
import api from '../../config/api';
@ -244,21 +81,29 @@ export const uploadDocuments = createAsyncThunk<
};
const toggle = state.selectedRecipients.transactionTemplateToggle;
console.log(`/api/accounts/${accountId}/${toggle}/${transactionId}/documents`)
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);
}
const response = await api.post(
`/api/accounts/${accountId}/${toggle}/${transactionId}/documents`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
);
console.log("// await sleep(5000);", response.data)
// await sleep(5000);
dispatch(hideLoader());
return [response.data];
return [...response];
} catch (error: any) {
dispatch(hideLoader());
@ -326,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

@ -55,10 +55,6 @@ export const updateSelectedDocuments = createAsyncThunk<
"selectedDocuments/updateSelectedDocuments",
async ({ documents }, { rejectWithValue }) => {
try {
console.log(documents, "From Selected Documents")
// await axiosInstance.post("/selected-documents",
// { documents }
// );

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 {
@ -405,8 +73,6 @@ export const addRecipientAsync = createAsyncThunk<
const updateRecipientsData = recipientsData.filter(recipient => recipient.id !== null);
const createRecipientsData = recipientsData.filter(recipient => recipient.id == null);
console.log("createRecipientsData", createRecipientsData)
const basePath = `/api/accounts/${accountId}/${toggle}/${transactionId}/recipients`;
const resUpdate = updateRecipientsData.length
@ -437,7 +103,6 @@ export const removeRecipientAsync = createAsyncThunk<
const basePath = `/api/accounts/${accountId}/${toggle}/${transactionId}/recipients`;
console.log(`Line 440 : ${basePath}/${recipientId}`)
// return
if (recipientId) {
await api.delete(`${basePath}/${recipientId}`);
@ -465,7 +130,11 @@ export const fetchRecipients = createAsyncThunk<
const basePath = `/api/accounts/${accountId}/${toggle}/${transactionId}/recipients`;
const response = await api.get(basePath);
const data = response.data as Recipient[];
let data = response.data as Recipient[];
// 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
@ -483,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

@ -23,7 +23,6 @@ const transactionSlice = createSlice({
reducers: {
setTransactionId: (state, action: PayloadAction<string>) => {
const transactionId = action.payload;
console.log("Mic Check 2", transactionId)
state.transactionId = transactionId;
return state;
},

View File

@ -10,12 +10,21 @@ const type_last_four = (str: string, changeWith: string): string => {
};
const type_credit_card = (str: string, changeWith: string): string => {
if (str.length !== 16) return str;
// console.log(str.replace(/\d(?=\d{4})/g, "*"), "line 11", str)
// return str.replace(/\d(?=\d{4})/g, `${changeWith}`);
return `${changeWith.repeat(4)} ${changeWith.repeat(4)} ${changeWith.repeat(4)} ${str.slice(-4)}`
if (str.length !== 15 && str.length !== 16) return str;
const last4 = str.slice(-4);
const masked = str.slice(0, -4).replace(/\d/g, changeWith);
if (str.length === 16) {
// Format: XXXX XXXX XXXX 1234
return masked.slice(0, 4) + " " + masked.slice(4, 8) + " " + masked.slice(8, 12) + " " + last4;
} else {
// 15-digit (Amex): XXXX XXXXXX X1234
return masked.slice(0, 4) + " " + masked.slice(4, 10) + " " + masked.slice(10, 11) + last4;
}
};
const type_national_insurance = (str: string, changeWith: string): string => {
// str = str.slice(0, -1).replace(/[A-Za-z0-9]/g, "*") + str.slice(-1);
// return str.replace(/\*/g, changeWith);
@ -40,7 +49,7 @@ const type_social_insurance = (str: string, changeWith: string): string => {
};
const maskUtils = (type: string, original: string, changeWith: string): string => {
switch (changeWith) {
case MASKCHARACTER.ASTERISK:
changeWith = "*";

View File

@ -40,8 +40,6 @@ const handleGroupBorderPosition = (groupElements: NodeListOf<HTMLElement>, conta
const borderBottom: HTMLElement | null = document.querySelector("[border-group='" + groupElements[0].getAttribute("group") + "'][border-pos='bottom']");
const borderLeft: HTMLElement | null = document.querySelector("[border-group='" + groupElements[0].getAttribute("group") + "'][border-pos='left']");
console.log("handleGroupBorderPosition")
if (borderTop !== null && dimension.maxLeft !== null && dimension.minLeft !== null) {
borderTop.style.width = (dimension.maxLeft - dimension.minLeft) + "px";
borderTop.style.height = "1px";

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,
@ -137,13 +132,13 @@ export interface StylesInterface {
textSize: number
}
export interface TagOptionAttrType{
label: string;
value: string;
pageIndex?: number;
selected?: boolean;
readOnly?: boolean;
dimensions?: Record<string, any>;
export interface TagOptionAttrType {
label: string;
value: string;
pageIndex?: number;
selected?: boolean;
readOnly?: boolean;
dimensions?: Record<string, any>;
}
@ -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