'use client'; import { FC, useMemo, useState } from "react"; import { BilledTo, BillingLocation, UserSettings } from "../lib/db-types"; import { formatYearMonth } from "../lib/format"; import { formatCurrency, formatIban } from "../lib/formatStrings"; import { useTranslations } from "next-intl"; import { ViewBillBadge } from "./ViewBillBadge"; import { Pdf417Barcode } from "./Pdf417Barcode"; import { EncodePayment, PaymentParams } from "hub-3a-payment-encoder"; import Link from "next/link"; import { DocumentIcon, LinkIcon } from "@heroicons/react/24/outline"; import { uploadUtilBillsProofOfPayment } from "../lib/actions/locationActions"; import QRCode from "react-qr-code"; export interface ViewLocationCardProps { location: BillingLocation; userSettings: UserSettings | null; } export const ViewLocationCard:FC = ({location, userSettings}) => { const { _id, name: locationName, yearMonth, bills, tenantName, tenantStreet, tenantTown, tenantPaymentMethod, // NOTE: only the fileName is projected from the DB to reduce data transfer utilBillsProofOfPaymentAttachment, utilBillsProofOfPaymentUploadedAt, } = location; const t = useTranslations("home-page.location-card"); const [isUploading, setIsUploading] = useState(false); const [uploadError, setUploadError] = useState(null); const [attachmentUploadedAt, setAttachmentUploadedAt ] = useState(utilBillsProofOfPaymentUploadedAt ?? null); const [attachmentFilename, setAttachmentFilename] = useState(utilBillsProofOfPaymentAttachment?.fileName); const handleFileChange = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; // Validate file type if (file.type !== 'application/pdf') { setUploadError('Only PDF files are accepted'); e.target.value = ''; // Reset input return; } setIsUploading(true); setUploadError(null); try { const formData = new FormData(); formData.append('utilBillsProofOfPaymentAttachment', file); const result = await uploadUtilBillsProofOfPayment(_id, formData); if (result.success) { setAttachmentFilename(file.name); setAttachmentUploadedAt(new Date()); } else { setUploadError(result.error || 'Upload failed'); } } catch (error: any) { setUploadError(error.message || 'Upload failed'); } finally { setIsUploading(false); e.target.value = ''; // Reset input } }; // sum all the billAmounts (only for bills billed to tenant) const monthlyExpense = bills.reduce((acc, bill) => (bill.paid && (bill.billedTo ?? BilledTo.Tenant) === BilledTo.Tenant) ? acc + (bill.payedAmount ?? 0) : acc, 0); const { hub3aText, paymentParams } = useMemo(() => { if(!userSettings?.enableIbanPayment || tenantPaymentMethod !== "iban") { return { hub3aText: "", paymentParams: {} as PaymentParams }; } const locationNameTrimmed_max20 = locationName.trimEnd().trimEnd().substring(0,19); const paymentParams:PaymentParams = { Iznos: (monthlyExpense/100).toFixed(2).replace(".",","), ImePlatitelja: tenantName ?? "", AdresaPlatitelja: tenantStreet ?? "", SjedistePlatitelja: tenantTown ?? "", Primatelj: userSettings?.ownerName ?? "", AdresaPrimatelja: userSettings?.ownerStreet ?? "", SjedistePrimatelja: userSettings?.ownerTown ?? "", IBAN: userSettings?.ownerIBAN ?? "", ModelPlacanja: "HR00", PozivNaBroj: formatYearMonth(yearMonth), SifraNamjene: "", OpisPlacanja: `Režije-${locationNameTrimmed_max20}-${formatYearMonth(yearMonth)}`, // max length 35 = "Režije-" (7) + locationName (20) + "-" (1) + "YYYY-MM" (7) }; return({ hub3aText: EncodePayment(paymentParams), paymentParams }); }, // eslint-disable-next-line react-hooks/exhaustive-deps []); return(

{formatYearMonth(yearMonth)} {locationName}

{ bills.filter(bill => (bill.billedTo ?? BilledTo.Tenant) === BilledTo.Tenant).map(bill => ) }
{ monthlyExpense > 0 ?

{ t("payed-total-label") } {formatCurrency(monthlyExpense, userSettings?.currency)}

: null } { userSettings?.enableIbanPayment && tenantPaymentMethod === "iban" ? <>

{t("payment-info-header")}

  • {t("payment-iban-label")}
    { formatIban(paymentParams.IBAN) }
  • {t("payment-recipient-label")}
    {paymentParams.Primatelj}
  • {t("payment-recipient-address-label")}
    {paymentParams.AdresaPrimatelja}
  • {t("payment-recipient-city-label")}
    {paymentParams.SjedistePrimatelja}
  • {t("payment-amount-label")}
    {paymentParams.Iznos} { userSettings?.currency }
  • {t("payment-description-label")}
    {paymentParams.OpisPlacanja}
  • {t("payment-model-label")}
    {paymentParams.ModelPlacanja}
  • {t("payment-reference-label")}
    {paymentParams.PozivNaBroj}
: null } { userSettings?.enableRevolutPayment && tenantPaymentMethod === "revolut" ? (() => { const revolutPaymentUrl = `https://revolut.me/${userSettings.ownerRevolutProfileName?.replace('@', '')}?amount=${(monthlyExpense).toFixed(0)}¤cy=${userSettings.currency}`; return ( <>

{t("payment-info-header")}

{t("revolut-link-text")}

); })() : null }
{t("upload-proof-of-payment-legend")} { // IF proof of payment was uploaded attachmentUploadedAt ? ( // IF file name is available, show link to download // ELSE it's not available that means that the uploaded file was purged by housekeeping // -> don't show anything attachmentFilename ? (
{decodeURIComponent(attachmentFilename)}
) : null ) : /* ELSE show upload input */ (
{isUploading && ( )}
{uploadError && (

{uploadError}

)}
)}
); };