How to display staff roster for given week

Viewed 42

I am trying to print a table of staff members and their shifts for given week.

I receive data in following format from the api.

[
  {
    full_name: 'Staff 1',
    schedule: [
      {
        day_of_week: 'tuesday',
        shifts: [
          {
            time_start: '9:00am',
            time_end: '6:00pm'
          }
        ]
      },
      {
        day_of_week: 'wednesday',
        shifts: [
          {
            time_start: '9:00am',
            time_end: '6:00pm'
          }
        ]
      },
    ]
  },
  {
    full_name: 'Staff 2',
    schedule: [
      {
        day_of_week: 'tuesday',
        shifts: [
          {
            time_start: '9:00am',
            time_end: '5:00pm'
          }
        ]
      },
      {
        day_of_week: 'thursday',
        shifts: [
          {
            time_start: '9:00am',
            time_end: '5:00pm'
          }
        ]
      }
    ]
  }
]

I also have given week like '2021-05-09' to '2021-05-15'.

How can I display their shift time in html table?

Result I want to achieve is the following table in picture with empty cell if that staff is not working on that day of the week and if working then time_start - time_end.

Thank you

enter image description here

1 Answers

The following will give you an array of arrays that represents your table data:

const arr=[ 
  {
full_name: 'Staff 1',
schedule: [
  {
    day_of_week: 'tuesday',
    shifts: [
      {
        time_start: '9:00am',
        time_end: '6:00pm'
      }
    ]
  },
  {
    day_of_week: 'wednesday',
    shifts: [
      {
        time_start: '9:00am',
        time_end: '6:00pm'
      }
    ]
  },
]
  },
  {
full_name: 'Staff 2',
schedule: [
  {
    day_of_week: 'tuesday',
    shifts: [
      {
        time_start: '9:00am',
        time_end: '5:00pm'
      }
    ]
  },
  {
    day_of_week: 'thursday',
    shifts: [
      {
        time_start: '9:00am',
        time_end: '5:00pm'
      }
    ]
  }
]
  }
],
dow="mon,tues,wednes,thurs,fri,satur,sun".split(",").map(d=>d+"day");
const res=arr.map(st=>{
    const ret=[st.full_name]; st.schedule.forEach(sc=>ret[dow.indexOf(sc.day_of_week)+1]=sc.shifts[0].time_start+" - "+sc.shifts[0].time_end);ret.length=8;
    return [...ret].map(r=>r??"")
})

days=["Crew",...dow.map((d,i)=>{
const t=new Date(),doff=t.getDay();
   t.setDate(t.getDate()-doff+1+i);
   return t.toLocaleString("en-GB",{weekday:"long",day:"numeric", month:"long"})
 })]    

console.log("array:",[days,...res]);

document.querySelector("table").innerHTML=
  "<thead><tr><th>"+days.join("</th><th>")
  +"</th></tr></thead>\n<tbody>"
  +res.map(tr=>"<tr><td>"+tr.join("</td><td>")+"</td></tr>").join("\n")
  +"</tbody>";
table { border: 1px solid #888 }
tbody>tr:nth-child(odd) {background-color:#ddd}
<table></table>

It should be fairly easy to translate that into an angular table (I have no angular experience).

Related