Weekly Payroll

Daily, weekly & hourly pay, extras, receipts & deductions

Cloud connection required. Sign in to continue.

Pay Period

TOTAL TO PAY
$0.00

Employee Payroll

Add Receipt

Tap Choose File to select Photo Library, Take Photo, or Browse (options depend on your iPhone browser). Images are compressed before saving.

Extra Hours by Property

Add Deduction

Record an advance or other adjustment. Check applicable wage deduction laws before withholding money from pay.

Attach a ticket, invoice or other supporting photo. The photo is saved with the deduction and included in the weekly payment PDF.

Receipts This Week

Work Schedule — Multiple Jobs

Separate from payroll. Add several addresses for one employee, then save all at once.

Import Work Schedule from Excel

Reads only the “Jordan Dont Touch” sheet. Other sheets are ignored. Review all rows and resolve names before importing. This does not update payroll.

Saved Work Entries

Employee Setup

Add up to 10 employees. Choose daily, weekly or hourly pay for each employee.

Crews / Teams

Create reusable crews. You can change membership at any time; previous assignments remain unchanged.

Employees

Saved Weeks

Backup & Restore

Backups include employees, weekly payroll, and saved receipt photos. Keep your backup file private.

`;let body=html.match(/([\s\S]*?)<\/body>/i)?.[1]||'';body=body.replace(/
[\s\S]*?<\/div>/,'');body += '

Weekly Work Log / Job Costing

Charge Amount and Check From are blank for handwritten entries.

' + ((s.workLogs||[]).map(x=>'').join('') || '') + '
EmployeeDateProperty AddressApt / AreaWork PerformedCharge Amount ($)Check From
'+safe(x.employeeName)+''+safe(x.date)+''+safe(x.address)+''+safe(x.unit||'General')+''+safe(x.description)+'
No work entries recorded
';let overlay=document.getElementById('payrollPrintOverlay');if(!overlay){overlay=document.createElement('div');overlay.id='payrollPrintOverlay';document.body.appendChild(overlay)}overlay.innerHTML='
'+body+'
';overlay.style.display='block';window.scrollTo(0,0)}function closePrintReport(){let o=document.getElementById('payrollPrintOverlay');if(o)o.style.display='none'}function viewSaved(w){alert(report(state.saved[w]))}function loadWeek(w){if(state.saved[w]?.closed)return alert("This week is closed. Use Reopen Week in History (owner only).");week=w;state.activeWeek=w;persist();tab('payroll')} // V19: safe snapshot editor for ANY saved period. Changes only saved reports, not unrelated active weeks. let historicalEdit=null; function editSavedWeek(w){ if(window.payrollUserRole!=='owner')return alert('Only the owner can edit saved payroll.'); if(!window.cloudReady)return alert('Cloud is not connected.'); const original=state.saved[w];if(!original)return alert('Saved period not found.'); historicalEdit={key:w,original:JSON.parse(JSON.stringify(original)),draft:JSON.parse(JSON.stringify(original))}; if(!Array.isArray(historicalEdit.draft.employees))historicalEdit.draft.employees=[]; drawHistoricalEditor(); } function histVal(v){return safe(String(v??''))} function histNum(v){const n=Number(v);return Number.isFinite(n)?n:0} function histEmployeeTotal(e){ const payType=['daily','weekly','hourly'].includes(e.payType)?e.payType:'daily'; const qty=histNum(e.quantity??e.days); e.basePay=Math.round(histNum(e.rate)*qty*100)/100; e.extraHoursPay=Math.round(histNum(e.extraHoursPay)*100)/100; e.extras=Math.round(histNum(e.extras)*100)/100; e.reimbursements=Math.round(histNum(e.reimbursements)*100)/100; e.deductions=Math.round(histNum(e.deductions)*100)/100; e.total=Math.round((e.basePay+e.extraHoursPay+e.extras+e.reimbursements-e.deductions)*100)/100; if(payType==='daily')e.days=qty; return e.total; } function histRecalculate(s){ const es=s.employees||[];s.wages=0;s.extras=0;s.days=0;s.extraHours=0;s.extraHoursPay=0;s.receipts=0;s.deductions=0;s.total=0; for(const e of es){histEmployeeTotal(e);s.wages+=e.basePay;s.extras+=histNum(e.extras);s.days+=histNum(e.days);s.extraHours+=histNum(e.extraHours);s.extraHoursPay+=histNum(e.extraHoursPay);s.receipts+=histNum(e.reimbursements);s.deductions+=histNum(e.deductions);s.total+=e.total;} for(const k of ['wages','extras','extraHoursPay','receipts','deductions','total'])s[k]=Math.round(s[k]*100)/100; } function histSet(i,k,v){ if(!historicalEdit)return;const e=historicalEdit.draft.employees[i];if(!e)return; if(k==='name'){e.name=String(v).trim();return} if(k==='payType'){e.payType=v;return} const n=Number(v);if(!Number.isFinite(n)||n<0){alert('Enter a non-negative number.');drawHistoricalEditor();return} e[k]=n; if(k==='quantity'&&e.payType==='daily')e.days=n; histRecalculate(historicalEdit.draft); const sum=document.getElementById('histEditTotal');if(sum)sum.textContent=money(historicalEdit.draft.total); const employeeTotal=document.getElementById('histTotal'+i);if(employeeTotal)employeeTotal.textContent=money(e.total); } function histAddWorker(){ if(!historicalEdit)return; const options=state.employees.filter(e=>!historicalEdit.draft.employees.some(x=>x.name.toLowerCase()===e.name.toLowerCase())); if(!options.length)return alert('All current employees are already in this period. You can rename an existing entry.'); const name=prompt('Employee name to add:\n'+options.map(e=>e.name).join(', '),options[0].name); if(name===null)return; const emp=options.find(e=>e.name.toLowerCase()===name.trim().toLowerCase());if(!emp)return alert('Choose an existing employee name from the list.'); historicalEdit.draft.employees.push({name:emp.name,rate:histNum(emp.rate),payType:emp.payType||'daily',quantity:0,days:0,basePay:0,extraHours:0,extraHoursPay:0,extras:0,reimbursements:0,deductions:0,total:0});drawHistoricalEditor(); } function histRemoveWorker(i){if(!historicalEdit)return;if(!confirm('Remove this employee from this saved report? The previous report will remain in Correction History.'))return;historicalEdit.draft.employees.splice(i,1);drawHistoricalEditor()} function histCancel(){document.getElementById('historicalEditor')?.remove();historicalEdit=null} function drawHistoricalEditor(){ if(!historicalEdit)return; histRecalculate(historicalEdit.draft); const d=historicalEdit.draft; document.getElementById('historicalEditor')?.remove(); const outer=document.createElement('div');outer.id='historicalEditor';outer.style.cssText='position:fixed;inset:0;z-index:20000;background:#091b31bd;overflow:auto;padding:12px;'; outer.innerHTML=`

Edit Saved Week

Owner only · Saved report corrections · Previous version retained

Edit worker names, pay type, days/hours, pay rates, extra hours pay, bonuses, reimbursements and deductions. This updates the saved report and printable forms, not the active payroll entries.

${d.employees.map((e,i)=>`
Worker ${i+1}${money(e.total)}
`).join('')}

Revised Total: ${money(d.total)}

`; document.body.appendChild(outer); } function histSave(){ if(!historicalEdit)return; if(window.payrollUserRole!=='owner'||!window.cloudReady)return alert('Owner and cloud connection required.'); const from=document.getElementById('histFrom').value,to=document.getElementById('histTo').value; if(!from||!to||to!e.name||!e.name.trim()))return alert('All employees need names.'); const oldKey=historicalEdit.key; if(from!==oldKey&&(state.saved[from]||state.weeks[from]))return alert('Another period already uses this start date. Choose another date.'); const d=historicalEdit.draft;d.week=from;d.endDate=to; histRecalculate(d); const old=historicalEdit.original; const prior={week:oldKey,at:new Date().toISOString(),by:'owner',reason:'Edit saved report',snapshot:old}; if(!confirm('Save corrected payroll for '+periodLabel(from,to)+'? The original report will be preserved in Correction History.'))return; (state.payrollCorrections||(state.payrollCorrections=[])).push(prior); d.closed=old.closed!==false;d.correctedAt=prior.at;d.previousReportCount=(old.previousReportCount||0)+1; if(from!==oldKey)delete state.saved[oldKey]; state.saved[from]=d; // Intentionally do not move original editable weeks or activeWeek: preserves all original work logs, receipts, and active payroll. if(!persist()){ state.payrollCorrections.pop();delete state.saved[from];state.saved[oldKey]=old;return; } histCancel();render();alert('Corrected report queued for cloud save. Verify the cloud revision changes before leaving the page.'); } function deleteSavedWeek(w){ if(window.payrollUserRole!=='owner')return alert('Only the owner can delete a payroll week.'); if(!window.cloudReady)return alert('Cloud is not connected. No changes were made.'); const saved=state.saved[w]; if(!saved)return alert('Week not found.'); if(!confirm('Are you sure you want to permanently delete the week '+periodLabel(w,saved.endDate)+'? This cannot be undone.'))return; const oldSaved=saved, oldWeek=state.weeks[w], oldActive=state.activeWeek, oldCurrent=week; delete state.saved[w]; delete state.weeks[w]; // Discard any previously archived copy of this same week as requested. if(state.deletedWeeks)delete state.deletedWeeks[w]; if(week===w||state.activeWeek===w){ const next=datePlus(saved.endDate||datePlus(w,6),1); week=next;state.activeWeek=next; } if(!persist()){ state.saved[w]=oldSaved; if(oldWeek!==undefined)state.weeks[w]=oldWeek; state.activeWeek=oldActive;week=oldCurrent; render();return; } render(); alert('Delete requested. Wait until Cloud Revision updates, then refresh History to confirm the week is gone.'); } function restoreDeletedWeek(w){ if(window.payrollUserRole!=='owner')return alert('Only the owner can restore a deleted week.'); if(!window.cloudReady)return alert('Cloud is not connected.'); const archive=state.deletedWeeks?.[w];if(!archive)return alert('Deleted week not found.'); if(state.saved[w]||state.weeks[w])return alert('A week with this start date already exists. Nothing was overwritten.'); if(!confirm('Restore '+periodLabel(w,archive.saved.endDate)+' to payroll history?'))return; state.saved[w]=archive.saved;if(archive.weekData!==null)state.weeks[w]=archive.weekData; delete state.deletedWeeks[w]; if(!persist()){ delete state.saved[w];delete state.weeks[w];state.deletedWeeks[w]=archive;return; } render();alert('Week restored. Verify the cloud revision updates.'); } function reopenWeek(w){ if(window.payrollUserRole!=='owner')return alert('Only the organization owner can reopen payroll.'); if(!window.cloudReady)return alert('Cloud is not connected.'); const saved=state.saved[w];if(!saved||!saved.closed)return alert('This pay period is not closed.'); if(!state.weeks[w])return alert('The original editable payroll records are missing. Do not reopen: restore requires a verified backup.'); if(!confirm('Reopen '+periodLabel(w,saved.endDate)+' for corrections? A copy of the original saved report will be kept in Correction History. Download a full backup first.'))return; const prior={week:w,at:new Date().toISOString(),by:'owner',snapshot:JSON.parse(JSON.stringify(saved))}; (state.payrollCorrections||(state.payrollCorrections=[])).push(prior); state.saved[w]={...saved,closed:false,reopenedAt:prior.at}; state.weeks[w].endDate=saved.endDate||state.weeks[w].endDate||datePlus(w,6); const oldWeek=week,oldActive=state.activeWeek;week=w;state.activeWeek=w; if(!persist()){state.payrollCorrections.pop();state.saved[w]=saved;week=oldWeek;state.activeWeek=oldActive;return} tab('payroll');alert('Week reopened. Edit payroll and select Finish Week to close again. Original saved report is in Correction History.'); }function backup(){download('weekly-payroll-backup-'+new Date().toISOString().slice(0,10)+'.json',JSON.stringify(state),'application/json')}async function restore(ev){let file=ev.target.files[0];if(!file)return;try{let data=JSON.parse(await file.text());if(!Array.isArray(data.employees)||!data.weeks||!data.saved)throw Error('Invalid backup');if(!confirm('Replace ALL shared cloud payroll data with this backup? Only do this during initial migration, with both managers signed out.'))return;let old=state;state=data;if(!persist()){state=old;return}render();alert('Backup restored.')}catch(e){alert('Invalid or unreadable backup file.')}ev.target.value=''}initPropertyCatalog();document.getElementById('receiptDate').value=new Date().toLocaleDateString('en-CA');document.getElementById('deductionDate').value=new Date().toLocaleDateString('en-CA');render(); let pdfEnginePromise; function ensurePdfEngine(){ if(typeof html2pdf==='function')return Promise.resolve(); if(!pdfEnginePromise)pdfEnginePromise=new Promise((resolve,reject)=>{ const script=document.createElement('script'); script.src='https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js'; script.onload=()=>typeof html2pdf==='function'?resolve():reject(new Error('PDF library unavailable')); script.onerror=()=>reject(new Error('Could not load PDF library')); document.head.appendChild(script); }).catch(e=>{pdfEnginePromise=null;throw e}); return pdfEnginePromise; } let nativePdfPromise; (function(){ 'use strict'; class jsPDF { constructor(opts={}){this.images=[];this.pages=[[]];this.pageSizes=[[opts.orientation==='landscape'?792:612,opts.orientation==='landscape'?612:792]];this.size=9;this.bold=false;this.color=[20,29,43];this.fill=[255,255,255];} addPage(orientation){this.pages.push([]);this.pageSizes.push(orientation==='landscape'?[792,612]:[612,792]);return this;} getNumberOfPages(){return this.pages.length;} setFont(f,style){this.bold=style==='bold';return this;} setFontSize(s){this.size=Number(s)||9;return this;} setTextColor(...c){this.color=c.length===1?[c[0],c[0],c[0]]:c;return this;} setFillColor(...c){this.fill=c.length===1?[c[0],c[0],c[0]]:c;return this;} splitTextToSize(value,width){const out=[];for(const para of String(value).split('\n')){let line='';for(const word of para.split(/\s+/)){let next=line?line+' '+word:word;if(next.length*this.size*.53>width&&line){out.push(line);line=word;}else line=next;}out.push(line);}return out;} text(value,x,y){const lines=Array.isArray(value)?value:[value];for(let i=0;i(Number(v)/255).toFixed(3));this.pages.at(-1).push(`${r} ${g} ${b} rg BT /${this.bold?'F2':'F1'} ${this.size} Tf 1 0 0 1 ${Number(x).toFixed(2)} ${(this.pageSizes.at(-1)[1]-Number(y)-i*this.size*1.3).toFixed(2)} Tm (${str}) Tj ET`);}return this;} rect(x,y,w,h,style){let c=style==='F'?this.fill:this.color;let [r,g,b]=c.map(v=>(Number(v)/255).toFixed(3));this.pages.at(-1).push(`${r} ${g} ${b} ${style==='F'?'rg':'RG'} ${Number(x)} ${this.pageSizes.at(-1)[1]-Number(y)-Number(h)} ${Number(w)} ${Number(h)} re ${style==='F'?'f':'S'}`);return this;} addImage(data,format,x,y,w,h){ if(typeof data!=='string'||!data.startsWith('data:image/jpeg;base64,'))throw Error('Receipt image must be JPEG'); const bin=atob(data.split(',')[1]);const bytes=Uint8Array.from(bin,c=>c.charCodeAt(0)); let width=0,height=0,pos=2; while(pos{const b=typeof v==='string'?encoder.encode(v):v;chunks.push(b);byteCount+=b.length}; const objects=[''];const add=x=>{objects.push(x);return objects.length-1}; const font1=add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>'); const font2=add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>'); const pagesId=add(''); const imageIds=this.images.map(im=>add({image:im})); const kids=[]; for(let pi=0;piim.page===pi?`/Im${i} ${imageIds[i]} 0 R`:'').filter(Boolean).join(' '); kids.push(add(`<< /Type /Page /Parent ${pagesId} 0 R /MediaBox [0 0 ${size[0]} ${size[1]}] /Resources << /Font << /F1 ${font1} 0 R /F2 ${font2} 0 R >> /XObject << ${imgs} >> >> /Contents ${contentId} 0 R >>`)); } objects[pagesId]=`<< /Type /Pages /Kids [${kids.map(id=>id+' 0 R').join(' ')}] /Count ${kids.length} >>`; const catalog=add(`<< /Type /Catalog /Pages ${pagesId} 0 R >>`); emit('%PDF-1.4\n%\xE2\xE3\xCF\xD3\n'); for(let i=1;i>\nstream\n`);emit(obj.stream);emit('\nendstream')} else if(obj.image){const im=obj.image;emit(`<< /Type /XObject /Subtype /Image /Width ${im.width} /Height ${im.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${im.bytes.length} >>\nstream\n`);emit(im.bytes);emit('\nendstream')} emit('\nendobj\n'); } const start=byteCount;emit(`xref\n0 ${objects.length}\n0000000000 65535 f \n`); for(let i=1;i>\nstartxref\n${start}\n%%EOF`); return new Blob(chunks,{type:'application/pdf'}); } } window.jspdf={jsPDF}; })(); function ensureNativePdfEngine(){ if(window.jspdf&&window.jspdf.jsPDF)return Promise.resolve(); if(!nativePdfPromise)nativePdfPromise=new Promise((resolve,reject)=>{ const script=document.createElement('script'); script.src='https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.2/jspdf.umd.min.js'; script.onload=()=>window.jspdf?.jsPDF?resolve():reject(new Error('PDF library unavailable')); script.onerror=()=>reject(new Error('PDF library could not load')); document.head.appendChild(script); }).catch(e=>{nativePdfPromise=null;throw e}); return nativePdfPromise; } async function generatePaymentForms(w){ const s=w?state.saved[w]:state.saved[week]; if(!s)return alert('Save Draft or Finish Week first, then generate forms.'); if(!s.employees||!s.employees.length)return alert('No employees in saved payroll.'); const m=n=>money(n),esc=safe,fmt=d=>{if(!d)return '';let x=new Date(d+'T12:00:00');return isNaN(x)?esc(d):x.toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'})}; const line=(label,val)=>`
${label}${val}
`; const summary=`

BRONX DEVELOPMENT GROUP PROPERTIES LLC

1118 LONGWOOD AVE, BRONX, NY 10474

WEEKLY PAYROLL SUMMARY

Payment period: ${fmt(s.week)} – ${fmt(s.endDate)}

${s.employees.map(e=>``).join('')}
WorkerBase PayExtra HoursExtrasReimbursementsDeductionsTotal
${esc(e.name)}${m(e.basePay)}${m(e.extraHoursPay)}${m(e.extras)}${m(e.reimbursements)}-${m(e.deductions)}${m(e.total)}

TOTAL TO PAY: ${m(s.total)}

Generated from saved payroll data. Verify all figures before payment.

`; const forms=s.employees.map(e=>{ const matches=x=>(x.employeeId&&e.id&&x.employeeId===e.id)||x.employeeName===e.name; const details=[]; if(Number(e.extras||0))details.push({type:'Extra Pay',description:e.extraReason||'Reason not specified',address:e.extraAddress||'Not specified',amount:Number(e.extras)}); const hourJobs=(s.hourJobs||[]).filter(matches); for(const j of hourJobs)details.push({type:'Extra Hours',description:`${j.hours} hours × ${m(j.rate)}/hour`,address:j.address||'Not specified',amount:Number(j.hours)*Number(j.rate)}); const otherHours=Number(e.extraHoursPay||0)-hourJobs.reduce((a,j)=>a+Number(j.hours)*Number(j.rate),0); if(otherHours>0.005)details.push({type:'Other Extra Hours',description:'Details not recorded',address:'Not specified',amount:otherHours}); for(const r of (s.receipts||[]).filter(matches))details.push({type:'Reimbursement',description:r.description||'Purchase / receipt',address:r.address||'Not specified',amount:Number(r.amount)}); for(const d of (s.deductionItems||[]).filter(matches))details.push({type:'Deduction',description:[d.reason,d.note].filter(Boolean).join(' — ')||'Reason not specified',address:d.address||'Not specified',amount:-Number(d.amount)}); const itemizedDeductions=details.filter(d=>d.type==='Deduction').reduce((a,d)=>a-d.amount,0); if(Number(e.deductions||0)-itemizedDeductions>0.005)details.push({type:'Deduction',description:'Prior adjustment — reason not recorded',address:'Not specified',amount:-(Number(e.deductions)-itemizedDeductions)}); const detailTable=`

ITEMIZED EXTRAS, HOURS, REIMBURSEMENTS & DEDUCTIONS

${details.map(d=>``).join('')||''}
TypeReason / DescriptionProperty AddressAmount
${esc(d.type)}${esc(d.description)}${esc(d.address)}${d.amount<0?'-':'+'}${m(Math.abs(d.amount))}
No additions or deductions recorded
`; return `

BRONX DEVELOPMENT GROUP PROPERTIES LLC

1118 LONGWOOD AVE, BRONX, NY 10474

WEEKLY PAYMENT CERTIFICATION & LIABILITY RELEASE

Worker Name: ${esc(e.name)}
Total Paid ($): ${m(e.total)}
Period From: ${fmt(s.week)}
Period To: ${fmt(s.endDate)}

1. LABOR, HOURS & COMPENSATION CERTIFICATION

• I hereby certify that my total work hours performed for the company during this specific payment period did not exceed 37 hours.

• I confirm that payment has been received in full for all services rendered, there is a zero balance remaining for this period, and no overtime work or compensation is involved on this project.

• I certify that I maintain active, fully compliant workers’ compensation coverage for myself and any personnel/helpers I utilize on the job site.

2. WORKPLACE SAFETY & INJURY REPORT

Did you experience, witness, or sustain any work-related injuries, accidents, or physical incidents during this specific work period? ☐ YES    ☐ NO

3. CLAIMS, LIENS & GENERAL LIABILITY RELEASE

Do you have any open claims, or do you intend to file any claims or demands against Bronx Development Group Properties LLC? ☐ YES    ☐ NO

By signing below, I acknowledge receipt of full compensation for this period. I hereby release, acquit, and forever discharge Bronx Development Group Properties LLC, its members, and affiliates from any and all liabilities, wage/hour claims, mechanics liens, material supplier liabilities, or demands of any nature arising out of services performed during this period.

4. SEPARATION / FINAL WEEK NOTICE (IF APPLICABLE)

☐ CHECK HERE IF THIS IS YOUR FINAL WEEK PERFORMING SERVICES FOR THE COMPANY

If checked above: I confirm that I am ending my business relationship and terminating my services voluntarily and by my own decision. I do not hold Bronx Development Group Properties LLC responsible for any liabilities, and I knowingly and voluntarily waive all future rights, claims, or demands related to my time providing services to the company.

WORKER / CONTRACTOR SIGNATURE
DATE SIGNED

WEEKLY PAY SUMMARY

${line('Pay type',esc(e.payType||'daily'))}${line('Days / Units',esc(e.quantity??e.days??0))}${line('Rate',m(e.rate))}${line('Regular pay',m(e.basePay))}${line('Extra hours',esc(e.extraHours||0)+' hrs / '+m(e.extraHoursPay))}${line('Extras',m(e.extras))}${line('Reimbursements',m(e.reimbursements))}${line('Deductions','-'+m(e.deductions))}${line('TOTAL PAID',m(e.total))}
${detailTable}

Generated from payroll records. Hours, receipt of payment, coverage, and legal declarations must be independently verified by the signer. This form does not establish legal compliance.

`; }).join(''); const html=`Weekly Payment Forms ${esc(s.week)}
${summary}${forms} `; // Generate one US Letter summary and one compact, original-style release form per worker. try{ await ensureNativePdfEngine(); const doc=new window.jspdf.jsPDF({orientation:'landscape',unit:'pt',format:'letter',compress:true}); const W=612,H=792,L=39,R=573,contentW=R-L; const pdfClean=v=>String(v??'').replace(/[\u2022\u2610\u2014\u2013\u00d7\u2019\u2018]/g,c=>({'•':'-','☐':'[ ]','—':'-','–':'-','×':'x','’':"'",'‘':"'"}[c]||c)); const text=(value,x,y,size=8,bold=false,width=contentW)=>{ doc.setFont('helvetica',bold?'bold':'normal');doc.setFontSize(size);doc.setTextColor(30,36,45); const lines=doc.splitTextToSize(pdfClean(value),width); const step=size*1.27; lines.forEach((line,i)=>doc.text(line,x,y+i*step)); return y+lines.length*step; }; const rule=(x,y,w,h,fill=false)=>{doc.setFillColor(242,243,245);doc.setTextColor(155,161,168);doc.rect(x,y,w,h,fill?'F':'S')}; const masthead=()=>{ text('BRONX DEVELOPMENT GROUP PROPERTIES LLC',92,43,13,true,440); text('1118 LONGWOOD AVE, BRONX, NY 10474',194,59,7.5,false,300); doc.setTextColor(130,130,130);doc.rect(L,69,contentW,0.5,'S'); }; const band=(label,y)=>{rule(L,y,contentW,20,true);text(label,L+10,y+13,9,true);return y+25}; const parsed=new DOMParser().parseFromString(html,'text/html'); const formNodes=[...parsed.querySelectorAll('article.page')].slice(1); const getRows=e=>{ const matches=x=>(x.employeeId&&e.id&&x.employeeId===e.id)||x.employeeName===e.name; const out=[]; if(Number(e.extras||0))out.push(['Extra Pay',e.extraReason||'Reason not specified',e.extraAddress||'Not specified',m(e.extras)]); const jobs=(s.hourJobs||[]).filter(matches); for(const j of jobs)out.push(['Extra Hours',`${j.hours} hours x ${m(j.rate)}/hour`,j.address||'Not specified',m(Number(j.hours)*Number(j.rate))]); const leftover=Number(e.extraHoursPay||0)-jobs.reduce((a,j)=>a+Number(j.hours)*Number(j.rate),0); if(leftover>0.005)out.push(['Extra Hours','Details not recorded','Not specified',m(leftover)]); for(const r of (s.receipts||[]).filter(matches))out.push(['Reimbursement',r.description||'Purchase / receipt',r.address||'Not specified',m(r.amount)]); const deductions=(s.deductionItems||[]).filter(matches); for(const d of deductions)out.push(['Deduction',[d.reason,d.note].filter(Boolean).join(' - ')||'Reason not specified',d.address||'Not specified','-'+m(d.amount)]); const remainder=Number(e.deductions||0)-deductions.reduce((a,d)=>a+Number(d.amount),0); if(remainder>0.005)out.push(['Deduction','Prior adjustment - reason not recorded','Not specified','-'+m(remainder)]); return out; }; // Landscape detailed summary: one employee per row, with every adjustment and its reason. const SW=792,SH=612,SL=30,SR=762,summaryWidth=SR-SL; const sumText=(value,x,y,size=7,bold=false,width=100)=>text(value,x,y,size,bold,width); const summaryHeader=(continued=false)=>{ sumText('BRONX DEVELOPMENT GROUP PROPERTIES LLC',SL,29,13,true,summaryWidth); sumText('1118 LONGWOOD AVE, BRONX, NY 10474',SL,44,8,false,summaryWidth); rule(SL,53,summaryWidth,1,true); sumText(continued?'WEEKLY PAYROLL - DETAILED SUMMARY (CONTINUED)':'WEEKLY PAYROLL - DETAILED SUMMARY',SL,69,11,true,summaryWidth); sumText('PAY PERIOD: '+fmt(s.week)+' - '+fmt(s.endDate||datePlus(s.week,6)),SL,83,8,false,summaryWidth); const y=94;rule(SL,y,summaryWidth,23,true); const cols=[SL+5,SL+103,SL+167,SL+206,SL+268,SL+336,SL+529,SL+690]; ['EMPLOYEE','RATE / TYPE','DAYS / UNITS','BASE PAY','HOURS PAY','EXTRAS / REIMBURSEMENTS','DEDUCTIONS / REASON','TOTAL'].forEach((v,i)=>sumText(v,cols[i],y+9,6.2,true,(cols[i+1]||SR)-cols[i]-5)); return {y:y+27,cols}; }; let sh=summaryHeader();let sy=sh.y; const summaryMatches=(x,e)=>(x.employeeId&&e.id&&x.employeeId===e.id)||x.employeeName===e.name; const summaryLines=(e)=>{ const extras=[];const deductions=[]; if(Number(e.extras||0))extras.push('+'+m(e.extras)+' Extra: '+(e.extraReason||'Reason not specified')+(e.extraAddress?' @ '+e.extraAddress:'')); const jobs=(s.hourJobs||[]).filter(j=>summaryMatches(j,e)); for(const j of jobs)extras.push('+'+m(Number(j.hours)*Number(j.rate))+' Hours: '+j.hours+'h x '+m(j.rate)+(j.address?' @ '+j.address:'')); const other=Number(e.extraHoursPay||0)-jobs.reduce((a,j)=>a+Number(j.hours)*Number(j.rate),0); if(other>.005)extras.push('+'+m(other)+' Extra hours: details not recorded'); for(const r of (s.receipts||[]).filter(r=>summaryMatches(r,e)))extras.push('+'+m(r.amount)+' Receipt: '+(r.description||'Purchase')+(r.address?' @ '+r.address:'')); const ds=(s.deductionItems||[]).filter(d=>summaryMatches(d,e)); for(const d of ds)deductions.push('-'+m(d.amount)+' '+[d.reason,d.note].filter(Boolean).join(' - ')+(d.address?' @ '+d.address:'')); const rest=Number(e.deductions||0)-ds.reduce((a,d)=>a+Number(d.amount),0); if(rest>.005)deductions.push('-'+m(rest)+' Prior adjustment (reason not recorded)'); return {extras,deductions}; }; for(const e of s.employees){ const detail=summaryLines(e),c=sh.cols; const wrap=(arr,w)=>arr.flatMap(v=>doc.splitTextToSize(pdfClean(v),w)); const ext=wrap(detail.extras.length?detail.extras:['-'],c[6]-c[5]-8); const ded=wrap(detail.deductions.length?detail.deductions:['-'],c[7]-c[6]-8); const rate=wrap([m(e.rate)+'/'+(e.payType==='weekly'?'week':e.payType==='hourly'?'hour':'day')],c[2]-c[1]-7); const height=Math.max(27,Math.max(ext.length,ded.length,rate.length)*9+12); if(sy+height>SH-76){doc.addPage('landscape');sh=summaryHeader(true);sy=sh.y;} const x=sh.cols; if((s.employees.indexOf(e)%2)===0)rule(SL,sy,summaryWidth,height,true); sumText(e.name,x[0],sy+12,7.7,true,x[1]-x[0]-5); rate.forEach((v,i)=>sumText(v,x[1],sy+12+i*9,6.8,false,x[2]-x[1]-5)); sumText(String(e.quantity??e.days??0),x[2],sy+12,7.4,false,x[3]-x[2]-5); sumText(m(e.basePay??Number(e.rate)*Number(e.quantity??e.days??0)),x[3],sy+12,7.4,false,x[4]-x[3]-5); sumText(m(e.extraHoursPay||0),x[4],sy+12,7.4,false,x[5]-x[4]-5); ext.forEach((v,i)=>sumText(v,x[5],sy+12+i*9,6.6,false,x[6]-x[5]-5)); ded.forEach((v,i)=>sumText(v,x[6],sy+12+i*9,6.6,false,x[7]-x[6]-5)); sumText(m(e.total),x[7],sy+12,8,true,SR-x[7]-3); doc.rect(SL,sy+height,summaryWidth,.3,'S');sy+=height; } if(sy+48>SH-24){doc.addPage('landscape');sh=summaryHeader(true);sy=sh.y;} rule(SL,sy+9,summaryWidth,32,true); sumText('TOTAL TO PAY: '+m(s.total),SL+10,sy+30,14,true,summaryWidth-20); sumText('Verify amounts, hours, and deductions before payment. Taxes and statutory overtime are not calculated.',SL,Math.min(SH-15,sy+55),7,false,summaryWidth); for(let i=0;ip.textContent.replace(/\s+/g,' ').trim()); const fontSize=title.startsWith('3.')?7.0:7.35; const lengths=paragraphs.map(p=>doc.splitTextToSize(pdfClean(p),contentW-20).length); const h=24+lengths.reduce((a,n)=>a+n*fontSize*1.27+4,0)+4; rule(L,yy,contentW,h,false);rule(L+1,yy+1,contentW-2,19,true); text(title,L+9,yy+13,8.4,true,contentW-18); let py=yy+30; for(const p of paragraphs){py=text(p,L+9,py,fontSize,false,contentW-20)+4;} yy+=h+7; } yy+=7; text('WORKER / CONTRACTOR SIGNATURE: _______________________________',L+2,yy,8.2); text('DATE SIGNED: ____________________',L+330,yy,8.2, false,200); yy+=16; yy=band('WEEKLY PAY SUMMARY',yy); const summaryRows=[ ['Pay type / units',String(e.payType||'daily')+' / '+String(e.quantity??e.days??0)], ['Rate / Regular pay',m(e.rate)+' / '+m(e.basePay)], ['Extra hours / Pay',String(e.extraHours||0)+' hrs / '+m(e.extraHoursPay)], ['Extras / Reimbursements',m(e.extras)+' / '+m(e.reimbursements)], ['Deductions / TOTAL PAID','-'+m(e.deductions)+' / '+m(e.total)] ]; for(let j=0;jH-44){doc.addPage();masthead();yy=band('PAY DETAILS - '+e.name+' (CONTINUED)',82)} yy=text(line1,L+9,yy+8,7.1,true,contentW-20)+1; yy=text(line2,L+9,yy,7.1,false,contentW-20)+5; doc.rect(L,yy,contentW,.25,'S');yy+=2; } if(yytypeof r.photo==='string'&&r.photo.startsWith('data:image/')); for(const receipt of photographedReceipts){ try{ const img=await new Promise((resolve,reject)=>{const i=new Image();i.onload=()=>resolve(i);i.onerror=()=>reject(Error('Unable to decode receipt photo'));i.src=receipt.photo}); const canvas=document.createElement('canvas');canvas.width=img.naturalWidth;canvas.height=img.naturalHeight; const ctx=canvas.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.drawImage(img,0,0); const jpeg=canvas.toDataURL('image/jpeg',0.85); doc.addPage('portrait'); text('BRONX DEVELOPMENT GROUP PROPERTIES LLC',L,38,12,true); text('RECEIPT / REIMBURSEMENT',L,60,12,true); text('Employee: '+(receipt.employeeName||s.employees.find(e=>e.id===receipt.employeeId)?.name||'Not specified'),L,86,10,true); text('Date: '+(receipt.date||'Not specified')+' Amount: '+m(receipt.amount),L,104,9); const addressBottom=text('Property: '+(receipt.address||'Not specified'),L,121,9,false,contentW); const descBottom=text('Description: '+(receipt.description||'Not specified'),L,addressBottom+5,9,false,contentW); const top=Math.max(166,descBottom+16),bottom=755,availableHeight=bottom-top; const scale=Math.min(contentW/img.naturalWidth,availableHeight/img.naturalHeight); const drawW=img.naturalWidth*scale,drawH=img.naturalHeight*scale; doc.addImage(jpeg,'JPEG',L+(contentW-drawW)/2,top,drawW,drawH); }catch(imageErr){ // Never silently omit an attached photo from a payment packet. throw new Error('Receipt photo could not be included ('+(receipt.employeeName||'employee')+'): '+imageErr.message); } } // Deduction evidence: one page per photo, following reimbursement receipts. for(const item of (s.deductionItems||[]).filter(d=>typeof d.photo==='string'&&d.photo.startsWith('data:image/'))){ try{ const img=await new Promise((resolve,reject)=>{const i=new Image();i.onload=()=>resolve(i);i.onerror=()=>reject(Error('Unable to decode deduction photo'));i.src=item.photo}); const canvas=document.createElement('canvas');canvas.width=img.naturalWidth;canvas.height=img.naturalHeight; const ctx=canvas.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.drawImage(img,0,0); const jpeg=canvas.toDataURL('image/jpeg',0.85); doc.addPage('portrait'); text('BRONX DEVELOPMENT GROUP PROPERTIES LLC',L,38,12,true); text('DEDUCTION / SUPPORTING PHOTO',L,60,12,true); text('Employee: '+(item.employeeName||s.employees.find(e=>e.id===item.employeeId)?.name||'Not specified'),L,86,10,true); text('Date: '+(item.date||'Not specified')+' Deduction: -'+m(item.amount),L,104,9); const addressBottom=text('Property: '+(item.address||'Not specified'),L,121,9,false,contentW); const reasonBottom=text('Reason: '+[item.reason,item.note].filter(Boolean).join(' - '),L,addressBottom+5,9,false,contentW); const top=Math.max(166,reasonBottom+16),bottom=755,availableHeight=bottom-top; const scale=Math.min(contentW/img.naturalWidth,availableHeight/img.naturalHeight); doc.addImage(jpeg,'JPEG',L+(contentW-img.naturalWidth*scale)/2,top,img.naturalWidth*scale,img.naturalHeight*scale); }catch(imageErr){throw new Error('Deduction photo could not be included ('+(item.employeeName||'employee')+'): '+imageErr.message)} } const blob=doc.output('blob'); if(blob.size<1500||doc.getNumberOfPages()URL.revokeObjectURL(url),60000); }catch(err){console.error('PDF export failed',err);alert('Could not generate the PDF: '+err.message+'. No payroll data was changed.');} } let excelPending=[]; function excelDate(value){if(value instanceof Date&&!isNaN(value))return value.toISOString().slice(0,10);if(typeof value==='number'&&value>30000&&value<80000){const d=new Date(Date.UTC(1899,11,30)+Math.round(value)*86400000);return d.toISOString().slice(0,10)}const s=String(value||'').trim();const m=s.match(/(?:mon(?:day)?|tue(?:sday)?|wed(?:nesday)?|thu(?:rsday)?|fri(?:day)?|sat(?:urday)?|sun(?:day)?)?\s*[,\-:]?\s*(\d{1,2})\s*[\/-]\s*(\d{1,2})(?:\s*[\/-]\s*(\d{2,4}))?/i);if(!m)return '';let year=m[3]?Number(m[3]):new Date().getFullYear();if(year<100)year+=2000;const mm=Number(m[1]),dd=Number(m[2]);if(mm<1||mm>12||dd<1||dd>31)return '';return year+'-'+String(mm).padStart(2,'0')+'-'+String(dd).padStart(2,'0')} function excelPerson(name){const n=String(name||'').trim().toLowerCase().replace(/\s+/g,' ');if(!n)return '';const crew=(state.crews||[]).find(c=>c.name.trim().toLowerCase()===n);if(crew)return 'crew:'+crew.id;const e=state.employees.find(e=>e.name.trim().toLowerCase()===n);if(e)return e.id;const parts=n.split(/\s*\+\s*|\s+and\s+/).filter(Boolean);if(parts.length>1){const ids=parts.map(p=>state.employees.find(e=>e.name.trim().toLowerCase()===p||e.name.trim().toLowerCase().split(' ')[0]===p)?.id);if(ids.every(Boolean)){const found=(state.crews||[]).find(c=>c.memberIds.length===ids.length&&ids.every(id=>c.memberIds.includes(id)));if(found)return 'crew:'+found.id}}return ''} function assignmentOptions(selected){return ''+state.employees.map(e=>'').join('')+(state.crews||[]).map(c=>'').join('')} async function previewScheduleExcel(event){const el=document.getElementById('excelImportPreview');excelPending=[];el.innerHTML='Reading file…';const f=event.target.files?.[0];if(!f)return;try{if(!window.XLSX)throw Error('Excel reader unavailable. Connect to the internet and reload.');const wb=XLSX.read(await f.arrayBuffer(),{type:'array',cellDates:true});const sheet=wb.Sheets['Jordan Dont Touch'];if(!sheet)throw Error('Sheet "Jordan Dont Touch" was not found.');const data=XLSX.utils.sheet_to_json(sheet,{header:1,defval:'',raw:true});let date='',person='',skipped=0;const parsed=[];for(let i=0;iNo work entries detected.

';return}const unresolved=excelPending.filter(x=>!x.key||!x.date||!x.address||!x.description).length;el.innerHTML='

'+excelPending.length+' rows detected · '+unresolved+' need review. Dates, assignments and missing fields must be checked. No payroll values are imported.

'+excelPending.map((x,i)=>'
Excel row '+x.row+' · Original: '+safe(x.person)+'
').join('')+'
'} function importExcelJobs(){if(!window.cloudReady)return alert('Cloud is not connected');const selected=excelPending.filter(x=>x.include);if(!selected.length)return alert('Select jobs to import');const bad=selected.filter(x=>!x.key||!x.date||!x.address.trim()||!x.description.trim()||!assignmentMembers(x.key).length);if(bad.length)return alert(bad.length+' selected rows are incomplete. Uncheck them or fix employee/crew, date, address and description.');const existing=new Set();for(const w of Object.values(state.weeks||{}))for(const x of (w.workLogs||[]))if(x.importKey)existing.add(x.importKey);let count=0,duplicates=0;const originalWeek=week;for(const x of selected){const members=assignmentMembers(x.key);const stamp=x.date+'|'+x.row+'|'+x.person+'|'+x.address+'|'+x.description;const importKey='excel:'+stamp;if(existing.has(importKey)){duplicates++;continue}const targetWeek=mondayFor(x.date);const w=state.weeks[targetWeek]||(state.weeks[targetWeek]={entries:{},receipts:[],hourJobs:[]});w.workLogs=w.workLogs||[];const crew=x.key.startsWith('crew:')?(state.crews||[]).find(c=>'crew:'+c.id===x.key):null;for(const e of members){w.workLogs.push({id:uid(),employeeId:e.id,employeeName:e.name,date:x.date,address:x.address,unit:x.unit,description:x.description,crewName:crew?.name||'',importKey,sourceSheet:'Jordan Dont Touch',sourceRow:x.row});count++}existing.add(importKey)}if(!count)return alert('No new entries. '+duplicates+' previously imported rows skipped.');persist();excelPending=[];document.getElementById('excelImportPreview').innerHTML='';render();alert(count+' employee job entries queued for cloud save; '+duplicates+' duplicates skipped. Check cloud saved revision before closing.');} function mondayFor(iso){const d=new Date(iso+'T12:00:00Z');const n=d.getUTCDay();d.setUTCDate(d.getUTCDate()-(n+6)%7);return d.toISOString().slice(0,10)}

Weekly Payroll Cloud

BX Development Group · Secure sign in