templates.js
1 import Head from "next/head"; 2 import { useState, useEffect, useRef } from "react"; 3 import { useMediaQuery } from "react-responsive"; 4 import { PDFDownloadLink } from "@react-pdf/renderer"; 5 import { PDF } from "../components/Preview/Preview"; 6 import styles from "@/styles/Home.module.scss"; 7 import logoP from "../assets/images/placeholder-image.png"; 8 import Previewed from "../components/Preview/Preview"; 9 import icblast from "@infu/icblast"; 10 import CRC32 from "crc-32"; 11 import Identity from "./identity"; 12 import NotesForm from "@/components/Form/NotesForm"; 13 import Payments from "../components/Payments/Payments"; 14 import CardWidget from "../components/Apps/CardWidgets"; 15 import PassportSwitcher from "../components/Passport/PassportSwitcher"; 16 import { OfferDB, NotesDB, TokenListDB, AccountRecordsDB } from "../components/Database/Database"; 17 import ReceiveModal from "../components/Wallet/ReceiveModal"; 18 import SendModal from "../components/Wallet/SendModal"; 19 import TransactionTokenSwitcher from "../components/Wallet/TransactionTokenSwitcher" 20 import ReceivePassport from "../components/Passport/ReceivePassport"; 21 import PresentPassport from "../components/Passport/PresentPassport"; 22 import OfferFormSwitcher from "../components/Form/OfferFormSwitcher"; 23 import PresentOffer from "../components/Form/PresentOffer"; 24 import useAuth from "../auth/hooks/useAuth"; 25 import WalletRelease from "../components/Repository/WalletRelease"; 26 27 28 const Templates = ({ searchResults }) => { 29 const { principal } = useAuth(); 30 const [principalId, setPrincipalId] = useState() 31 const [formData, setFormData] = useState({}); 32 const [showPreview, setShowPreview] = useState(false); 33 const [rows, setRows] = useState( 34 Array(1).fill({ id: 0, quantity: 1, amount: "0.00" }), 35 ); 36 const [logo, setLogo] = useState(logoP); 37 const [logoUpdated, setLogoUpdated] = useState(false); 38 const [currencySymbol, setCurrencySymbol] = useState("$"); 39 const [currencyCode, setCurrencyCode] = useState("USDT"); 40 const [template, setTemplate] = useState(null); 41 const [templateSelected, setTemplateSelected] = useState(false); 42 const [total, setTotal] = useState(0); 43 const [pdfFile, setPdfFile] = useState(null); //For file upload 44 const [pdfGenerated, setPdfGenerated] = useState(false); 45 const [notesFormData, setNotesFormData] = useState(); 46 const [showWalletReceiveModal, setShowWalletReceiveModal] = useState(false); 47 const [showWalletSendModal, setShowWalletSendModal] = useState(false); 48 const [showPassportReceiveModal, setShowPassportReceiveModal] = useState(false); 49 const [showPassportPresentModal, setShowPassportPresentModal] = useState(false); 50 const [showOfferPresentModal, setShowOfferPresentModal] = useState(false); 51 const [tableData, setTableData] = useState(null); 52 const [tableAmount, setTableAmount] = useState(null); 53 const [tableTotal, setTableTotal] = useState(null); 54 const [selectedAccount, setSelectedAccount] = useState(null); 55 const [latestBalance, setLatestBalance] = useState(null); 56 const [offerRecipientAddress, setOfferRecipientAddress] = useState(); 57 58 const isMobile = useMediaQuery({ query: `(max-width: 760px)` }); 59 60 // const { identity, principalId, walletCanister } = useAuth(); 61 useEffect(() => { 62 console.log("Principal in templates: ", principal); 63 setPrincipalId(principal); 64 }, [principal]); 65 66 const handlePaymentMethodModify = (selectedMethod) => { 67 setSelectedPaymentMethod(selectedMethod); 68 }; 69 70 const handleTemplateChange = (e) => { 71 setTemplate(e.target.value); 72 if (e.target.value) setTemplateSelected(true); 73 74 setTimeout(() => { 75 window.scroll({ 76 top: isMobile ? 1800 : 500, 77 behavior: "smooth", 78 }); 79 }, 400); 80 }; 81 82 const handleLogoUpdate = (e) => { 83 const reader = new FileReader(); 84 reader.onload = () => { 85 if (reader.readyState === 2) { 86 setLogo(reader.result); 87 setLogoUpdated(true); 88 } 89 }; 90 reader.readAsDataURL(e.target.files[0]); 91 }; 92 93 const handleFormChange = (name, value) => { 94 let updatedFormData; 95 if ( 96 typeof value === "object" && 97 "target" in value && 98 "value" in value.target 99 ) { 100 updatedFormData = { 101 ...formData, 102 [name]: value.target.value, 103 }; 104 } else { 105 updatedFormData = { 106 ...formData, 107 [name]: value, 108 }; 109 } 110 setFormData(updatedFormData); 111 console.log("Form data updated:" ,formData); 112 }; 113 114 //.........Wallet Implementations............ 115 116 //Handle selelcted token 117 const handleSelectedAccount = (account) => { 118 console.log("Selected account at templates: ", account) 119 setSelectedAccount(account); 120 } 121 122 //Checkout iframe function 123 const iframeRef = useRef(); 124 125 126 const sendCheckoutDetailsToIdentity = () => { 127 alert(iframeRef.current) 128 let purchaseDetails = { type: "name", value: "Tswaanda" }; 129 parent.postMessage( 130 JSON.stringify(purchaseDetails), 131 "*", 132 ); 133 }; 134 135 const sendOfferDetailsToIdentity = () => { 136 let purchaseDetails = { type: "name", value: "Tswaanda" }; 137 iframeRef.current.contentWindow.postMessage( 138 JSON.stringify(purchaseDetails), 139 "*", 140 ); 141 }; 142 143 const sendPurchaseDetailsToIdentity = () => { 144 let purchaseDetails = { 145 type: "purchase", 146 value: { 147 walletOwner: "", 148 accountNumber: "", 149 paymentDate: "", 150 orderNumber: "", 151 }, 152 }; 153 iframeRef.current.contentWindow.postMessage( 154 JSON.stringify(purchaseDetails), 155 "*", 156 ); 157 }; 158 159 const sendExportDetailsToIdentity = () => { 160 let purchaseDetails = { type: "export", value: "" }; 161 iframeRef.current.contentWindow.postMessage( 162 JSON.stringify(purchaseDetails), 163 "*", 164 ); 165 }; 166 167 const sendShipmentDetailsToIdentity = () => { 168 let purchaseDetails = { type: "shipment", value: "" }; 169 iframeRef.current.contentWindow.postMessage( 170 JSON.stringify(purchaseDetails), 171 "*", 172 ); 173 }; 174 175 const sendFulfillmentDetailsToIdentity = () => { 176 let purchaseDetails = { type: "fulfillment", value: "" }; 177 iframeRef.current.contentWindow.postMessage( 178 JSON.stringify(purchaseDetails), 179 "*", 180 ); 181 }; 182 183 const sendDisputeDetailsToIdentity = () => { 184 let purchaseDetails = { type: "dispute", value: "" }; 185 }; 186 187 const sendSupportMessageToIdentity = () => { 188 let message = { type: "message", value: "Hello, how can I help you?" }; 189 iframeRef.current.contentWindow.postMessage(JSON.stringify(message), "*"); 190 }; 191 192 const renderActions = () => { 193 if (template === "template1") { 194 return ( 195 <> 196 ACTIONS 197 <br /> 198 <br /> 199 <button className={styles.action__btn} onClick={handleToggle}> 200 {showPreview ? "Back to Edit" : "Preview"} 201 </button> 202 <br /> 203 <br /> 204 <div> 205 <PDFDownloadLink 206 document={pdf} 207 fileName={`${formData.clientName}_${formData.formName}.pdf`} 208 > 209 {({ blob, url, loading, error }) => ( 210 <button 211 className={styles.action__btn} 212 disabled={!showPreview} 213 onClick={handleOfferPresentModalToggle} 214 > 215 Submit 216 </button> 217 )} 218 </PDFDownloadLink> 219 </div> 220 <br /> 221 <br /> 222 </> 223 ); 224 } else if (template === "template2") { 225 return ( 226 <> 227 ACTIONS 228 <br /> 229 <br /> 230 <button className={styles.action__btn} onClick={handleToggle}> 231 {showPreview ? "Back to Edit" : "Preview"} 232 </button> 233 <br /> 234 <br /> 235 <div> 236 <PDFDownloadLink 237 document={pdf} 238 fileName={`${formData.clientName}_${formData.formName}.pdf`} 239 > 240 {({ blob, url, loading, error }) => ( 241 <button 242 className={styles.action__btn} 243 disabled={!showPreview} 244 onClick={handleOfferPresentModalToggle} 245 > 246 Submit 247 </button> 248 )} 249 </PDFDownloadLink> 250 </div> 251 <br /> 252 <br /> 253 </> 254 ); 255 } else if (template === "template3") { 256 return ( 257 <> 258 ACTIONS 259 <br /> 260 <br /> 261 <button 262 className={styles.action__btn} 263 onClick={sendCheckoutDetailsToIdentity} 264 > 265 Seller 266 </button> 267 <br /> 268 <br /> 269 <button 270 className={styles.action__btn} 271 onClick={sendCheckoutDetailsToIdentity} 272 > 273 Buyer 274 </button> 275 <br /> 276 <br /> 277 278 </> 279 ); 280 } else if (template === "template4") { 281 return ( 282 <> 283 ACTIONS 284 <br /> 285 <br /> 286 <button 287 className={styles.action__btn} 288 onClick={handleWalletReceiveModalToggle} 289 > 290 Recieve 291 </button> 292 <br /> 293 <br /> 294 <div> 295 <button 296 className={styles.action__btn} 297 onClick={handleWalletSendModalToggle} 298 > 299 Send 300 </button> 301 </div> 302 <br /> 303 <br /> 304 </> 305 ); 306 } else if (template === "template5") { 307 return ( 308 <> 309 ACTIONS 310 <br /> 311 <br /> 312 <button 313 className={styles.action__btn} 314 onClick={handlePassportReceiveModalToggle} 315 > 316 Receive 317 </button> 318 <br /> 319 <br /> 320 <div> 321 <button 322 className={styles.action__btn} 323 onClick={handlePassportPresentModalToggle} 324 > 325 Present 326 </button> 327 </div> 328 <br /> 329 <br /> 330 </> 331 ); 332 } else if (template === "template6") { 333 return ( 334 <> 335 ACTIONS 336 <br /> 337 <br /> 338 <button 339 className={styles.action__btn} 340 onClick={handleWalletReceiveModalToggle} 341 > 342 Recieve 343 </button> 344 <br /> 345 <br /> 346 <div> 347 <PDFDownloadLink 348 document={pdf} 349 fileName={`${formData.clientName}_${formData.formName}.pdf`} 350 > 351 {({ blob, url, loading, error }) => ( 352 <button 353 className={styles.action__btn} 354 disabled={!showPreview} 355 onClick={handleSubmit} 356 > 357 Send 358 </button> 359 )} 360 </PDFDownloadLink> 361 </div> 362 <br /> 363 <br /> 364 </> 365 ); 366 } else if (template === "template7") { 367 return ( 368 <> 369 ACTIONS 370 <br /> 371 <br /> 372 <button 373 className={styles.action__btn} 374 //onClick={handleWalletReceiveModalToggle} 375 > 376 Create 377 </button> 378 <br /> 379 <br /> 380 <button 381 className={styles.action__btn} 382 //onClick={handleWalletReceiveModalToggle} 383 > 384 Add release 385 </button> 386 <br /> 387 <br /> 388 </> 389 ); 390 } 391 return null; 392 }; 393 394 const handleWalletReceiveModalToggle = () => { 395 setShowWalletReceiveModal(!showWalletReceiveModal); 396 }; 397 398 const handleWalletSendModalToggle = () => { 399 setShowWalletSendModal(!showWalletSendModal); 400 }; 401 402 const handlePassportReceiveModalToggle = () => { 403 setShowPassportReceiveModal(!showPassportReceiveModal); 404 }; 405 406 const handlePassportPresentModalToggle = () => { 407 setShowPassportPresentModal(!showPassportPresentModal); 408 }; 409 410 const handleOfferPresentModalToggle = () => { 411 setShowOfferPresentModal(!showOfferPresentModal); 412 }; 413 414 const handleToggle = () => { 415 if (!showPreview) { 416 let generatedPdf; 417 418 switch (template) { 419 case "template1": 420 generatedPdf = ( 421 <PDF 422 template={template} 423 rows={rows} 424 email={formData.email} 425 businessName={formData.businessName} 426 formName={formData.formName} 427 logo={logo} 428 logoUpdated={logoUpdated} 429 address={formData.address} 430 city={formData.city} 431 zipcode={formData.zipcode} 432 phone={formData.phone} 433 owner={formData.owner} 434 clientName={formData.clientName} 435 clientEmail={formData.clientEmail} 436 clientAddress={formData.clientAddress} 437 clientCity={formData.clientCity} 438 clientZipcode={formData.clientZipcode} 439 clientPhone={formData.clientPhone} 440 date={formData.date} 441 invoiceNo={formData.invoiceNo} 442 website={formData.website} 443 notes={formData.notes} 444 currencySymbol={currencySymbol} 445 totalAmount={total} 446 /> 447 ); 448 break; 449 450 case "template2": 451 generatedPdf = ( 452 <PDF 453 template={template} 454 rows={rows} 455 email={formData.email} 456 businessName={formData.businessName} 457 formName={formData.formName} 458 logo={logo} 459 logoUpdated={logoUpdated} 460 address={formData.address} 461 city={formData.city} 462 zipcode={formData.zipcode} 463 phone={formData.phone} 464 owner={formData.owner} 465 clientName={formData.clientName} 466 clientEmail={formData.clientEmail} 467 clientAddress={formData.clientAddress} 468 clientCity={formData.clientCity} 469 clientZipcode={formData.clientZipcode} 470 clientPhone={formData.clientPhone} 471 date={formData.date} 472 invoiceNo={formData.invoiceNo} 473 website={formData.website} 474 notes={formData.notes} 475 currencySymbol={currencySymbol} 476 totalAmount={total} 477 /> 478 ); 479 480 addServicesData(); 481 break; 482 483 case "template3": 484 generatedPdf = ( 485 <PDF 486 template={template} 487 rows={rows} 488 email={formData.email} 489 businessName={formData.businessName} 490 formName={formData.formName} 491 logo={logo} 492 logoUpdated={logoUpdated} 493 address={formData.address} 494 city={formData.city} 495 zipcode={formData.zipcode} 496 phone={formData.phone} 497 owner={formData.owner} 498 clientName={formData.clientName} 499 clientEmail={formData.clientEmail} 500 clientAddress={formData.clientAddress} 501 clientCity={formData.clientCity} 502 clientZipcode={formData.clientZipcode} 503 clientPhone={formData.clientPhone} 504 date={formData.date} 505 invoiceNo={formData.invoiceNo} 506 website={formData.website} 507 notes={formData.notes} 508 currencySymbol={currencySymbol} 509 totalAmount={total} 510 /> 511 ); 512 addNotesData(); 513 break; 514 515 default: 516 break; 517 } 518 if (generatedPdf) { 519 setPdfFile(generatedPdf); 520 setPdfGenerated(true); 521 } 522 } 523 setShowPreview(!showPreview); 524 setPdfFile(null); 525 setPdfGenerated(false); 526 }; 527 528 // Table Functions 529 const handleTableUpdate = (e, id, amount) => { 530 setRows((prevRows) => { 531 const updateTable = [...prevRows]; 532 const currentRowIndex = updateTable.findIndex((row) => row.id === id); 533 updateTable[currentRowIndex] = { 534 ...updateTable[currentRowIndex], 535 [e.target.name]: e.target.value, 536 }; 537 if (amount !== undefined) { 538 updateTable[currentRowIndex].amount = amount; 539 } 540 if (e.target.name === "rate" || e.target.name === "quantity") { 541 updateTable[currentRowIndex][e.target.name] = Number(e.target.value); 542 } 543 return updateTable; 544 }); 545 }; 546 const handleRowAdd = () => { 547 const lastId = rows.length ? rows[rows.length - 1].id : 0; 548 setRows((prevRows) => [ 549 ...prevRows, 550 { id: lastId + 1, quantity: 1, amount: "0.00" }, 551 ]); 552 }; 553 554 const handleRowRemove = (id) => { 555 setRows((prevRows) => prevRows.filter((item) => item.id !== id)); 556 }; 557 const handleCurrencyModify = (curr) => { 558 setCurrencyCode(curr.code); 559 setCurrencySymbol(curr.symbol); 560 }; 561 562 function numberWithCommas(x) { 563 return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 564 } 565 566 const calculateTotal = () => { 567 let sum = 0; 568 rows.forEach((row) => { 569 sum += parseFloat(row.amount); 570 }); 571 setTotal(numberWithCommas(sum.toFixed(2))); 572 }; 573 574 useEffect(() => { 575 calculateTotal(); 576 }, [rows]); 577 578 //Form submit function 579 const handleCargoFormSubmit = async (data) => { 580 try { 581 setFormData(data); 582 583 const ic = icblast({ identity }); 584 const repository_canister = await ic("chs73-3aaaa-aaaar-qabaa-cai"); 585 //copies wallet into a variable if there is an exisitng wallet 586 let wallet_response = await repository_canister.copy_wallet_code(); 587 console.log("Here is wallet address(existing):", wallet_response); 588 //Create wallet from the principalId of the caller 589 let user_wallet_address = 590 await repository_canister.check_wallet_of(principalId); 591 setUserWalletAddress(user_wallet_address); 592 console.log("Here is your wallet address(new):", user_wallet_address); 593 //Get wallet address of the call 594 let wallet_address = await repository_canister.check_wallet(); 595 //The wallet constant created here will be used to create the contract canister 596 const wallet = await ic(wallet_address.toString()); 597 console.log("Wallet:", wallet); 598 //Mint contract canister from wallet 599 let contract_address = await wallet.mint_contract(); 600 let contract = await ic(contract_address.toString); 601 console.log(contract); 602 //converting data to JSON 603 // const jsonData = JSON.stringify(data); 604 let offerSubmit = await contract.start_offer(data); 605 606 console.log("Data to be submitted:", offerSubmit); 607 console.log("This is the Data:", data); 608 } catch (error) { 609 console.log("The issue:", error); 610 } 611 }; 612 613 //Pdf change function 614 const handlePdfFileChange = (event) => { 615 const file = event.target.files[0]; 616 if (file) { 617 const reader = new FileReader(); 618 reader.onload = () => { 619 if (reader.readyState === 2) { 620 setPdfFile(new Uint8Array(reader.result)); 621 } 622 }; 623 reader.readAsArrayBuffer(file); 624 } 625 }; 626 627 const handleCrprFileUpload = async (pdfFile, walletCanister) => { 628 const batch_id = "crpr_file"; 629 const asset_uint8Array = new Uint8Array(pdfFile); 630 const chunkSize = 2000000; 631 let checksum = 0; 632 const chunkIds = []; 633 const lastChunkSize = asset_uint8Array.length % chunkSize; 634 const isLastChunk = lastChunkSize !== 0; 635 636 for ( 637 let start = 0, index = 0; 638 start < asset_uint8Array.length; 639 start += chunkSize, index++ 640 ) { 641 let chunkSizeToUse = chunkSize; 642 643 // If it's the last chunk and it's smaller than chunkSize, use the actual size 644 if ( 645 isLastChunk && 646 index === Math.floor(asset_uint8Array.length / chunkSize) 647 ) { 648 chunkSizeToUse = lastChunkSize; 649 } 650 651 const chunk = asset_uint8Array.slice(start, start + chunkSizeToUse); 652 653 const chunkChecksum = updateChecksum(chunk, checksum); 654 console.log("Chunk Checksum:", chunkChecksum); 655 656 const chunkId = index; 657 658 chunkIds.push(chunkId); 659 660 console.log("Array of chunk identifiers:", chunkIds); 661 662 try { 663 const response = await walletCanister.upload_crpr_file({ 664 checksum: chunkChecksum, 665 chunk_ids: chunkIds, //Array of chunk identifiers 666 file_type: "application/pdf", 667 content_encoding: { GZIP: null }, 668 }); 669 console.log("Chunk upload response:", response); 670 } catch (error) { 671 console.error("Error uploading chunk:", error); 672 } 673 } 674 }; 675 676 // Function to calculate updated checksum 677 function updateChecksum(chunk, checksum) { 678 const moduloValue = 400000000; // Range: 0 to 400_000_000 679 const signedChecksum = CRC32.buf(Buffer.from(chunk, "binary"), 0); 680 const unsignedChecksum = signedChecksum >>> 0; 681 const updatedChecksum = (checksum + unsignedChecksum) % moduloValue; 682 return updatedChecksum; 683 } 684 685 const fileQueryUrl = async (walletCanister) => { 686 try { 687 const queryResponse = await walletCanister.query_crpr_file_url(); 688 console.log("Here is the file query url: ", queryResponse); 689 } catch (queryError) { 690 console.error("Failed to get query url:", queryError); 691 } 692 }; 693 694 const handleSubmit = () => { 695 console.log("Form Data: ", formData); 696 console.log("...Submitting to database...."); 697 addOfferData(); 698 if (pdfGenerated) { 699 handleCrprFileUpload(pdfFile, walletCanister); 700 addCargoData(); 701 console.log("Submit Crpr pdf sucessfully: ", pdfFile); 702 } else { 703 console.log("Please generate the PDF first"); 704 } 705 }; 706 707 const handleOfferPresentData = (data) => { 708 console.log("Recipient data: ", data); 709 setOfferRecipientAddress(data) 710 } 711 712 const handleOfferSubmit = () => { 713 console.log("Form Data: ", formData); 714 console.log("...Submitting to database...."); 715 addOfferData(); 716 addTokenListData(); 717 addAccountRecordsData(); 718 } 719 720 const handleTableData = (tableData, amount, total) => { 721 setTableData((prevTableData) => { 722 return tableData; 723 }); 724 setTableAmount((prevTableAmount) => { 725 return amount; 726 }); 727 setTableTotal((prevTableTotal)=> { 728 return total; 729 }); 730 731 console.log("Table Data in templates: ", tableData); 732 console.log("Table Amount in templates: ", amount); 733 console.log("Table total in templates: ", total); 734 }; 735 736 737 const { 738 businessName, 739 email, 740 address, 741 city, 742 zipcode, 743 phone, 744 website, 745 invoiceNo, 746 date, 747 jurisdiction, 748 clientName, 749 clientEmail, 750 clientAddress, 751 clientCity, 752 clientZipcode, 753 clientPhone, 754 currency, 755 businessPlatform, 756 counterOffer, 757 cargoInsurance, 758 couterPartyInsurance, 759 notes, 760 } = formData; 761 762 //writing cargo and servies data to offer database 763 const addOfferData = async () => { 764 try { 765 const formDetails = { 766 companyName: businessName, 767 companyEmail: email, 768 companyAddress: `${zipcode}, ${address}, ${city}`, 769 companyPhoneNumber: phone, 770 companyWebiste: website, 771 invoiceNumber: invoiceNo, 772 maturityDate: date, 773 jurisdiction: jurisdiction, 774 customer_clientName: clientName, 775 customer_clientEmail: clientEmail, 776 customer_clientAddress: `${clientZipcode}, ${clientAddress}, ${clientCity} `, 777 customer_clientPhoneNumber: clientPhone, 778 currency: currency, 779 businessPlatform: businessPlatform, 780 counterOffer: counterOffer, 781 cargoInsurance: cargoInsurance, 782 counterpartyInsurance: couterPartyInsurance, 783 totalAmount: total, 784 terms: notes, 785 timestamp: new Date(), 786 }; 787 const tableRowsDetails = rows.map((row) => ({ 788 product_serviceId: row.id, 789 product_serviceName: row.description, 790 product_serviceDescription: row.details, 791 rate: row.rate, 792 quantity: row.quantity, 793 weight: row.weight, 794 amount: row.amount, 795 })); 796 797 await Promise.all([ 798 OfferDB.offerDetails.add({...formDetails, ...tableRowsDetails}) 799 ]); 800 } catch (error) { 801 console.log( 802 "There was an issue with writing to the offer database: ", 803 error, 804 ); 805 } 806 }; 807 // writing details from offer to TokenList database in order to create new account with token. 808 const addTokenListData = async () => { 809 try { 810 await TokenListDB.tokenListDetails.add({ 811 accountName: businessName, 812 currency: currency, 813 balance: 0, 814 }) 815 } catch(error) { 816 console.log("There was an issue writing to token list database: ",error); 817 } 818 } 819 820 //Writing account records details to account records database 821 const addAccountRecordsData = async () => { 822 if(!principal) { 823 console.log("Could not find source principal, make sure you are logged in"); 824 return; 825 } 826 try { 827 await AccountRecordsDB.accountRecordsDetails.add({ 828 accountName: businessName, 829 state: "Offer", 830 currency: currency, 831 offerAmount: total, 832 dueDate: date, 833 nativeBalance: 0, 834 usdBalance: 0, 835 sourcePrincipal: principalId, 836 destinationPrincipal: offerRecipientAddress, 837 timestamp: new Date(), 838 }) 839 } catch(error) { 840 console.log("There was an issue writing to the account records database: ", error); 841 } 842 } 843 844 845 //Call back function to fetch Notes Data from NotesForm component 846 const handleNotesData = (notesData) => { 847 console.log("Found notes data in templates page: ", notesData); 848 setNotesFormData(notesData); 849 }; 850 851 //Adding data to Notes Database 852 const addNotesData = async () => { 853 try { 854 await NotesDB.notesDetails.add(notesFormData); 855 } catch (error) { 856 console.log( 857 "There was an issue with adding notes data to database: ", 858 error, 859 ); 860 } 861 }; 862 863 const renderForm = () => { 864 if (template === "template1") { 865 return ( 866 <OfferFormSwitcher 867 prefill={formData} 868 rows={rows} 869 logo={logo} 870 updateLogo={handleLogoUpdate} 871 logoUpdated={logoUpdated} 872 currencySymbol={currencySymbol} 873 onFormMod={handleFormChange} 874 onPreviewToggle={handleToggle} 875 onRowAdd={handleRowAdd} 876 onRowRemove={handleRowRemove} 877 onTableUpdate={handleTableUpdate} 878 handleTableData={handleTableData} 879 /> 880 ); 881 } else if (template === "template2") { 882 return ( 883 <NotesForm 884 prefill={formData} 885 rows={rows} 886 logo={logo} 887 updateLogo={handleLogoUpdate} 888 logoUpdated={logoUpdated} 889 currencySymbol={currencySymbol} 890 onFormMod={handleFormChange} 891 onPreviewToggle={handleToggle} 892 onRowAdd={handleRowAdd} 893 onRowRemove={handleRowRemove} 894 onTableUpdate={handleTableUpdate} 895 handleNotesData={handleNotesData} 896 /> 897 ); 898 } else if (template === "template3") { 899 return <Identity />; 900 } else if (template === "template4") { 901 return <TransactionTokenSwitcher 902 handleSelectedAccount={handleSelectedAccount} 903 />; 904 } else if (template === "template5") { 905 return <PassportSwitcher />; 906 } else if (template === "template6") { 907 return <Payments />; 908 } else if (template === "template7") { 909 return <WalletRelease /> 910 } 911 }; 912 913 const pdf = ( 914 <PDF 915 template={template} 916 rows={rows} 917 email={formData.email} 918 businessName={formData.businessName} 919 formName={formData.formName} 920 logo={logo} 921 logoUpdated={logoUpdated} 922 address={formData.address} 923 city={formData.city} 924 zipcode={formData.zipcode} 925 phone={formData.phone} 926 owner={formData.owner} 927 clientName={formData.clientName} 928 clientEmail={formData.clientEmail} 929 clientAddress={formData.clientAddress} 930 clientCity={formData.clientCity} 931 clientZipcode={formData.clientZipcode} 932 clientPhone={formData.clientPhone} 933 date={formData.date} 934 invoiceNo={formData.invoiceNo} 935 website={formData.website} 936 notes={formData.notes} 937 currencySymbol={currencySymbol} 938 totalAmount={total} 939 /> 940 ); 941 942 return ( 943 <> 944 <Head> 945 <title>Hanse</title> 946 <meta name="description" content="Generated by create next app" /> 947 <meta name="viewport" content="width=device-width, initial-scale=1" /> 948 <link rel="icon" href="/favicon.ico" /> 949 </Head> 950 951 <main> 952 <div className={styles.template__wrapper}> 953 <div> 954 {showWalletReceiveModal && ( 955 <ReceiveModal 956 open={showWalletReceiveModal} 957 onClose={handleWalletReceiveModalToggle} 958 /> 959 )} 960 </div> 961 <div> 962 {showWalletSendModal && ( 963 <SendModal 964 open={showWalletSendModal} 965 onClose={handleWalletSendModalToggle} 966 selectedAccount={selectedAccount} 967 /> 968 )} 969 </div> 970 <div> 971 {showPassportReceiveModal && ( 972 <ReceivePassport 973 open={showPassportReceiveModal} 974 onClose={handlePassportReceiveModalToggle} 975 selectedToken={selectedToken} 976 /> 977 )} 978 </div> 979 <div> 980 {showPassportPresentModal && ( 981 <PresentPassport 982 open={showPassportPresentModal} 983 onClose={handlePassportPresentModalToggle} 984 /> 985 )} 986 </div> 987 <div> 988 {showOfferPresentModal && ( 989 <PresentOffer 990 onOfferSubmit={handleOfferSubmit} 991 open={showOfferPresentModal} 992 onClose={handleOfferPresentModalToggle} 993 onOfferPresentData={handleOfferPresentData} 994 /> 995 )} 996 </div> 997 <div className={styles.container}> 998 <CardWidget 999 template={template} 1000 changeTemplate={handleTemplateChange} 1001 searchResult={searchResults} 1002 /> 1003 {templateSelected && ( 1004 <div className={styles.template__section}> 1005 <div className={styles.main__section}> 1006 {!showPreview && renderForm()} 1007 {showPreview && ( 1008 <Previewed 1009 {...formData} 1010 rows={rows} 1011 logo={logo} 1012 logoUpdated={logoUpdated} 1013 template={template} 1014 currencySymbol={currencySymbol} 1015 onPreviewToggle={handleToggle} 1016 /> 1017 )} 1018 </div> 1019 <div className={styles.action__section}> 1020 <div className={styles.actions}>{renderActions()}</div> 1021 </div> 1022 </div> 1023 )} 1024 </div> 1025 </div> 1026 </main> 1027 </> 1028 ); 1029 }; 1030 1031 export default Templates;