How to use shiftDate method in Cypress

Best JavaScript code snippet using cypress

ShiftScheduler.js

Source:ShiftScheduler.js Github

copy

Full Screen

1import PropTypes from 'prop-types';2import React, { Component } from 'react';3import moment from 'moment';4import DatePicker from 'material-ui/DatePicker';5import TimePicker from 'material-ui/TimePicker';6import Divider from 'material-ui/Divider';7import AddCircle from 'material-ui/svg-icons/content/add-circle';8import RemoveCircle from 'material-ui/svg-icons/content/remove-circle';9import s from 'styles/Form.scss';10const blankShift = (11  date = moment()12    .startOf('day')13    .toDate(),14) => ({15  id: undefined,16  start: undefined,17  end: moment(date)18    .add(16, 'hour')19    .toDate(),20  startError: null,21  endError: null,22});23class ShiftScheduler extends Component {24  static propTypes = {25    data: PropTypes.object.isRequired,26    submit: PropTypes.func.isRequired,27  };28  constructor(props) {29    super(props);30    // TODO change to Date objects?31    const shifts = props.data.shifts.length === 0 ? [blankShift()] : props.data.shifts;32    const shiftDates = [];33    shifts.forEach((shift) => {34      const placeholderShift = typeof shift.start === 'undefined';35      const shiftDate = placeholderShift36        ? undefined37        : moment(shift.start)38            .startOf('day')39            .toDate();40      const foundIndex = placeholderShift ? -1 : shiftDates.findIndex((d) => moment(d.date).isSame(shiftDate, 'day'));41      const newShift = {42        id: shift.id,43        start: moment(shift.start).toDate(),44        end: moment(shift.end).toDate(),45        startError: null,46        endError: null,47      };48      if (foundIndex === -1) {49        shiftDates.push({ date: shiftDate, dateError: null, shifts: [newShift] });50      } else {51        shiftDates[foundIndex].shifts.push(newShift);52      }53    });54    this.state = { shiftDates };55  }56  componentDidUpdate() {57    if (this.errorElem) {58      this.errorElem.scrollIntoView();59    }60  }61  validate = () => {62    let hasErrors = false;63    const newShiftDates = this.state.shiftDates.map((shiftDate) => {64      const newShiftDate = { ...shiftDate };65      newShiftDate.dateError = null;66      if (typeof newShiftDate.date !== 'object') {67        hasErrors = true;68        newShiftDate.dateError = 'Date required';69      }70      const newShifts = newShiftDate.shifts.map((shift) => {71        let shiftError = false;72        const newShift = { ...shift };73        newShift.startError = null;74        newShift.endError = null;75        if (typeof newShift.start !== 'object') {76          shiftError = true;77          newShift.startError = 'Starting time required';78        }79        if (typeof shift.end !== 'object') {80          shiftError = true;81          newShift.endError = 'Starting time required';82        }83        if (!shiftError) {84          if (!moment(newShift.end).isAfter(moment(newShift.start))) {85            shiftError = true;86            newShift.endError = 'End time must be before start';87          }88        }89        hasErrors = hasErrors || shiftError;90        return newShift;91      });92      newShiftDate.shifts = newShifts;93      return newShiftDate;94    });95    this.setState({ shiftDates: newShiftDates });96    return hasErrors;97  };98  formSubmit = () => {99    const hasErrors = this.validate();100    if (!hasErrors) {101      const shifts = this.state.shiftDates.reduce((accumulator, shiftDate) => {102        const newShifts = shiftDate.shifts.map((shift) => ({103          start: moment(shift.start).format(),104          end: moment(shift.end).format(),105          id: shift.id,106        }));107        return [...accumulator, ...newShifts];108      }, []);109      this.props.submit({ shifts });110    }111  };112  addDate = () => {113    const newShifts = [...this.state.shiftDates];114    const newDate = moment()115      .startOf('day')116      .toDate();117    newShifts.push({ date: newDate, dateError: null, shifts: [blankShift(newDate)] });118    this.setState({ shiftDates: newShifts });119  };120  addShift = (dateIndex) => {121    const newShifts = [...this.state.shiftDates];122    const { date } = newShifts[dateIndex];123    newShifts[dateIndex].shifts.push(blankShift(date));124    this.setState({ shiftDates: newShifts });125  };126  removeDate = (dateIndex) => {127    const newShifts = [...this.state.shiftDates];128    newShifts.splice(dateIndex, 1);129    this.setState({ shiftDates: newShifts });130  };131  removeShift = (dateIndex, shiftIndex) => {132    const newShifts = [...this.state.shiftDates];133    newShifts[dateIndex].shifts.splice(shiftIndex, 1);134    this.setState({ shiftDates: newShifts });135  };136  changeShift = (type, time, dateIndex, shiftIndex) => {137    const newShifts = [...this.state.shiftDates];138    const date = moment(this.state.shiftDates[dateIndex].date);139    const mTime = moment(time);140    const newTime = date.hour(mTime.hour()).minute(mTime.minute());141    newShifts[dateIndex].shifts[shiftIndex][type] = newTime.toDate();142    newShifts[dateIndex].shifts[shiftIndex][`${type}Error`] = null;143    this.setState({ shiftDates: newShifts });144  };145  changeDate = (dateIndex, date) => {146    const newShifts = [...this.state.shiftDates];147    newShifts[dateIndex].date = date;148    newShifts[dateIndex].dateError = null;149    const mDate = moment(date);150    // eslint-disable-next-line no-restricted-syntax151    for (const shift of newShifts[dateIndex].shifts) {152      shift.start = moment(shift.start)153        .date(mDate.date())154        .month(mDate.month())155        .year(mDate.year())156        .toDate();157      shift.end = moment(shift.end)158        .date(mDate.date())159        .month(mDate.month())160        .year(mDate.year())161        .toDate();162    }163    this.setState({ shiftDates: newShifts });164  };165  render() {166    const { shiftDates } = this.state;167    const { formSubmit, addShift, addDate, changeDate, changeShift, removeShift, removeDate } = this;168    const formatDate = (date) => moment(date).format('M/D/YYYY');169    const dialogStyle = {170      zIndex: '3200',171    };172    const renderDateForm = (shiftDate, dateIndex) => {173      const renderedShifts = shiftDate.shifts.map((shift, shiftIndex) => (174        <div key={JSON.stringify(shift)} className={s.shiftContainer}>175          <div176            className={s.shiftPicker}177            ref={(input) => {178              if (shift.startError || shift.endError) {179                this.errorElem = input;180              }181            }}182          >183            <div className={s.shiftLabel}>184              <span>Shift {shiftIndex + 1}:</span>185            </div>186            <TimePicker187              floatingLabelText="Start Time"188              value={shift.start}189              errorText={shift.startError}190              minutesStep={5}191              onChange={(event, time) => {192                changeShift('start', time, dateIndex, shiftIndex);193              }}194              className={s.shiftTimePicker}195            />196            <TimePicker197              floatingLabelText="End Time"198              value={shift.end}199              errorText={shift.endError}200              minutesStep={5}201              onChange={(event, time) => {202                changeShift('end', time, dateIndex, shiftIndex);203              }}204              className={s.shiftTimePicker}205            />206          </div>207          {shiftIndex > 0 && (208            <div className={s.removeShiftContainer}>209              <div210                onClick={(event) => {211                  event.preventDefault();212                  removeShift(dateIndex, shiftIndex);213                }}214                onKeyPress={(event) => {215                  event.preventDefault();216                  removeShift(dateIndex, shiftIndex);217                }}218                role="button"219                tabIndex="0"220                className={s.touchIcon}221              >222                <RemoveCircle />223                Remove Shift224              </div>225            </div>226          )}227        </div>228      ));229      return (230        <div className={s.dateWithShiftsContainer}>231          <div className={s.dateShiftContainer}>232            <div233              className={s.textFieldContainer}234              ref={(input) => {235                if (shiftDate.dateError) {236                  this.errorElem = input;237                }238              }}239            >240              <DatePicker241                value={shiftDate.date}242                errorText={shiftDate.dateError}243                onChange={(event, date) => {244                  changeDate(dateIndex, date);245                }}246                container="dialog"247                dialogContainerStyle={dialogStyle}248                floatingLabelText="Date"249                formatDate={formatDate}250                className={s.dateShiftPicker}251              />252            </div>253            {dateIndex > 0 && (254              <div className={s.removeDateContainer}>255                <div256                  onClick={(event) => {257                    event.preventDefault();258                    removeDate(dateIndex);259                  }}260                  onKeyPress={(event) => {261                    event.preventDefault();262                    removeDate(dateIndex);263                  }}264                  role="button"265                  tabIndex="0"266                  className={s.touchIcon}267                >268                  <RemoveCircle />269                  Remove Date270                </div>271              </div>272            )}273          </div>274          {renderedShifts}275          <div276            onClick={(event) => {277              event.preventDefault();278              addShift(dateIndex);279            }}280            onKeyPress={(event) => {281              event.preventDefault();282              addShift(dateIndex);283            }}284            role="button"285            tabIndex="0"286            className={s.touchIcon}287          >288            <AddCircle />289            Add Shift290          </div>291          <Divider />292        </div>293      );294    };295    const dateForm = shiftDates.map((shiftDate, index) => renderDateForm(shiftDate, index));296    return (297      <div className={s.outerContainer}>298        <div className={s.innerContainer}>299          <div className={s.formContainer}>300            <form className={s.form} onSubmit={formSubmit}>301              <div className={s.sectionLabel}>When:</div>302              {dateForm}303              <div304                onClick={(event) => {305                  event.preventDefault();306                  addDate();307                }}308                onKeyPress={(event) => {309                  event.preventDefault();310                  addDate();311                }}312                role="button"313                tabIndex="0"314                className={s.touchIcon}315              >316                <AddCircle />317                Add Date318              </div>319            </form>320          </div>321        </div>322      </div>323    );324  }325}...

Full Screen

Full Screen

Shifts.js

Source:Shifts.js Github

copy

Full Screen

1import React, { useState, useEffect, useCallback } from "react";2import axios from "axios";3import { DataGrid } from '@material-ui/data-grid';4import { Button } from "@material-ui/core";5const baseURL = process.env.HOST_IP_ADDRESS ? process.env.HOST_IP_ADDRESS : ""6export default function Shifts(props) {7  // TODO: get employeeName from shifts api instead of looking through entire userbase8  // TODO: fix date9  const qs = require('qs');10  const [shiftData, setShiftData] = useState({});11  const [userData, setUserData] = useState(null);12  const [isEditing, setIsEditing] = useState(false);13  const initialNewShiftRow = {14    id: 0,15    employeeName: props.user.name,16    shiftDate: new Date(),17    start: "",18    finish: "",19    break: ""20  };21  const [newShiftRow, setNewShiftRow] = useState(initialNewShiftRow);22  useEffect(() => {23    axios.get(baseURL + "/api/v1/organisations/" + props.organisation.id + "/shifts.json")24      .then(response => setShiftData(response.data));25    axios.get(baseURL + "/api/v1/users.json")26      .then(response => setUserData(response.data));27  }, [props.organisation.id]);28  // DataGrid stuff29  const columns = [30    { field: "employeeName", headerName: "Employee name", flex: 1.2, editable: true },31    { field: "shiftDate", headerName: "Shift date", type: "date", flex: 1, editable: true },32    { field: "start", headerName: "Start time", type: "string", flex: 1, editable: true },33    { field: "finish", headerName: "End time", type: "string", flex: 1, editable: true },34    { field: "break", headerName: "Break length (minutes)", type: "string", flex: 1.2, editable: true },35    { field: "hours", headerName: "Hours worked", type: "string", flex: 1, editable: true },36    { field: "cost", headerName: "Shift cost", type: "string", flex: 0.9, editable: true },37  ];38  const generateRows = () =>39    shiftData.data.map((shift, index) => {40      const hours_worked = calculateHoursWorked(41        shift.attributes.start,42        shift.attributes.finish,43        shift.attributes.break_length);44      const cost = calculateCost(45        hours_worked,46        props.organisation.attributes.hourly_rate)47      return {48        id: index + 1,49        employeeName: userData.filter((user) => { return user.id === shift.attributes.user_id })[0].name,50        shiftDate: parseDate(shift.attributes.start),51        start: parseTime(shift.attributes.start),52        finish: parseTime(shift.attributes.finish),53        break: shift.attributes.break_length,54        hours: hours_worked,55        cost: "$" + cost56      }57    });58  const newShiftButton = () =>59    <React.Fragment>60      <Button61        variant="contained"62        color="primary"63        style={{ margin: "10px" }}64        onClick={() => {65          if (isEditing) {66            postShift();67          }68          setIsEditing(!isEditing);69        }}70      >71        {isEditing ? "Save" : "New Shift"}72      </Button>73      {isEditing ?74        <Button75          variant="contained"76          color="secondary"77          style={{ margin: "10px 0px " }}78          onClick={() => setIsEditing(false)}79        >80          Cancel81        </Button> : null}82    </React.Fragment>83  const handleEditCellChangeCommitted = useCallback(84    ({ id, field, props }) => {85      switch (field) {86        case "employeeName":87          setNewShiftRow({ ...newShiftRow, employeeName: props.value, });88          break;89        case "shiftDate":90          setNewShiftRow({ ...newShiftRow, shiftDate: new Date(props.value), });91          break;92        case "start":93          setNewShiftRow({ ...newShiftRow, start: props.value, });94          break;95        case "finish":96          setNewShiftRow({ ...newShiftRow, finish: props.value, });97          break;98        case "break":99          setNewShiftRow({ ...newShiftRow, break: props.value, });100          break;101        default:102          return;103      }104    }, [newShiftRow],105  );106  function postShift() {107    axios.post("/api/v1/shifts", qs.stringify(108      {109        shift: {110          start: string2ISODateString(newShiftRow.shiftDate, newShiftRow.start),111          finish: string2ISODateString(newShiftRow.shiftDate, newShiftRow.finish),112          break_length: parseInt(newShiftRow.break),113          organisation_id: parseInt(props.organisation.id),114          user_id: props.user.id115        }116      }), { withCredentials: true })117      .then(response => {118        setShiftData({119          "data": [120            ...shiftData.data,121            response.data.data122          ]123        });124        setNewShiftRow(initialNewShiftRow);125      })126  };127  // Helper functions /////////////////////////////////////////////////////////128  function string2ISODateString(dateObject, timeString) {129    const splitTime = timeString.split(":");130    const date = new Date(131      dateObject.getFullYear(), dateObject.getMonth(),132      dateObject.getDate(), parseInt(splitTime[0]), parseInt(splitTime[1]));133    return date.toISOString();134  };135  function parseDate(dateTimeString) {136    const date = new Date(dateTimeString);137    return date.toLocaleDateString("en-AU");138  };139  function parseTime(dateTimeString) {140    const date = new Date(dateTimeString);141    return date.toString().split(" ")[4].slice(0, 5)142  };143  function calculateHoursWorked(start, end, break_length) {144    const startDate = new Date(start);145    const endDate = new Date(end);146    return (((endDate - startDate) / 1000 / 60 / 60) - (break_length / 60)).toFixed(2);147  };148  function calculateCost(hours_worked, rate) {149    return (hours_worked * rate).toFixed(2);150  };151  /////////////////////////////////////////////////////////////////////////////152  return (153    <div style={{ height: 200, width: '100%' }}>154      <div style={{ display: 'flex', height: '100%' }}>155        <div style={{ flexGrow: 1 }}>156          {userData && shiftData.data ?157            <DataGrid158              rows={isEditing ? [...generateRows(), newShiftRow] : generateRows()}159              columns={columns}160              autoHeight161              isCellEditable={(params) => params.row.id === 0}162              onEditCellChangeCommitted={handleEditCellChangeCommitted}163              components={{164                Footer: newShiftButton,165              }}166            /> : null}167        </div>168      </div>169    </div>170  )...

Full Screen

Full Screen

shift-date.state.js

Source:shift-date.state.js Github

copy

Full Screen

1(function() {2    'use strict';3    angular4        .module('shiftworkApp')5        .config(stateConfig);6    stateConfig.$inject = ['$stateProvider'];7    function stateConfig($stateProvider) {8        $stateProvider9        .state('shift-date', {10            parent: 'entity',11            url: '/shift-date',12            data: {13                authorities: ['ROLE_USER'],14                pageTitle: 'shiftworkApp.shiftDate.home.title'15            },16            views: {17                'content@': {18                    templateUrl: 'app/entities/shift-date/shift-dates.html',19                    controller: 'ShiftDateController',20                    controllerAs: 'vm'21                }22            },23            resolve: {24                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {25                    $translatePartialLoader.addPart('shiftDate');26                    $translatePartialLoader.addPart('dayOfWeek');27                    $translatePartialLoader.addPart('global');28                    return $translate.refresh();29                }]30            }31        })32        .state('shift-date-detail', {33            parent: 'entity',34            url: '/shift-date/{id}',35            data: {36                authorities: ['ROLE_USER'],37                pageTitle: 'shiftworkApp.shiftDate.detail.title'38            },39            views: {40                'content@': {41                    templateUrl: 'app/entities/shift-date/shift-date-detail.html',42                    controller: 'ShiftDateDetailController',43                    controllerAs: 'vm'44                }45            },46            resolve: {47                translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {48                    $translatePartialLoader.addPart('shiftDate');49                    $translatePartialLoader.addPart('dayOfWeek');50                    return $translate.refresh();51                }],52                entity: ['$stateParams', 'ShiftDate', function($stateParams, ShiftDate) {53                    return ShiftDate.get({id : $stateParams.id});54                }]55            }56        })57        .state('shift-date.new', {58            parent: 'shift-date',59            url: '/new',60            data: {61                authorities: ['ROLE_USER']62            },63            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {64                $uibModal.open({65                    templateUrl: 'app/entities/shift-date/shift-date-dialog.html',66                    controller: 'ShiftDateDialogController',67                    controllerAs: 'vm',68                    backdrop: 'static',69                    size: 'lg',70                    resolve: {71                        entity: function () {72                            return {73                                dayIndex: null,74                                date: null,75                                dayOfWeek: null,76                                id: null77                            };78                        }79                    }80                }).result.then(function() {81                    $state.go('shift-date', null, { reload: true });82                }, function() {83                    $state.go('shift-date');84                });85            }]86        })87        .state('shift-date.edit', {88            parent: 'shift-date',89            url: '/{id}/edit',90            data: {91                authorities: ['ROLE_USER']92            },93            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {94                $uibModal.open({95                    templateUrl: 'app/entities/shift-date/shift-date-dialog.html',96                    controller: 'ShiftDateDialogController',97                    controllerAs: 'vm',98                    backdrop: 'static',99                    size: 'lg',100                    resolve: {101                        entity: ['ShiftDate', function(ShiftDate) {102                            return ShiftDate.get({id : $stateParams.id});103                        }]104                    }105                }).result.then(function() {106                    $state.go('shift-date', null, { reload: true });107                }, function() {108                    $state.go('^');109                });110            }]111        })112        .state('shift-date.delete', {113            parent: 'shift-date',114            url: '/{id}/delete',115            data: {116                authorities: ['ROLE_USER']117            },118            onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) {119                $uibModal.open({120                    templateUrl: 'app/entities/shift-date/shift-date-delete-dialog.html',121                    controller: 'ShiftDateDeleteController',122                    controllerAs: 'vm',123                    size: 'md',124                    resolve: {125                        entity: ['ShiftDate', function(ShiftDate) {126                            return ShiftDate.get({id : $stateParams.id});127                        }]128                    }129                }).result.then(function() {130                    $state.go('shift-date', null, { reload: true });131                }, function() {132                    $state.go('^');133                });134            }]135        });136    }...

Full Screen

Full Screen

tcfsubmit.js

Source:tcfsubmit.js Github

copy

Full Screen

1const express = require('express');2const router = express.Router();3const momenttz = require('moment-timezone');4const { google } = require('googleapis');5const keys = require('../tcfentries.json')6const TCFEntries = require('../models/tvfentries');7const Agenttask = require('../models/agenttasks');8router.post('/', async (req, res)=>{9    try {10        if (req.session.user_id){11            const {tasktypeSelect, project, catalogtcf, Hrs, Min, Sec, status, assignedby, billtype} = req.body12            let Manila = momenttz.tz(new Date(), "Asia/Manila");13            let servertime = Manila.format('L LTS')14            // sectomin = parseFloat(Sec) / 6015            mintohr = parseFloat(Min) / 6016            finalhr = parseFloat(Hrs) + mintohr17            console.log(finalhr)18            const shiftEnries =  await Agenttask.find({taskName: 'Shift'}).sort({created_at: -1}).limit(1)19            const shiftdate = shiftEnries[0].ShiftDate20            console.log(shiftdate)21            22            // const tcfEntry = new TCFEntries ({23            //     ShiftDate: shiftdate,24            //     TaskType: tasktypeSelect,25            //     Project: project,26            //     Catalog: catalogtcf,27            //     Hrs: Hrs,28            //     Min: Min,29            //     Sec: Sec,30            //     TotalHrs: finalhr,31            //     Status: status,32            //     AssignedBy: assignedby,33            //     BillingType: billtype,34            //     addedby: req.session.user_id,35            //     ServerTime: servertime36            // })37            // await tcfEntry.save()38            39            let values = [40                [41                    shiftdate,42                    tasktypeSelect,43                    project,44                    catalogtcf,45                    Hrs,46                    Min,47                    Sec,48                    finalhr,49                    status,50                    assignedby,51                    billtype,52                    req.session.user_id,53                    servertime54                ]55            ]56            const resource = {57                values58            }59            const client = new google.auth.JWT(60                keys.client_email,61                null,62                keys.private_key,63                ['https://www.googleapis.com/auth/spreadsheets']64            )65            client.authorize(function(err, tokens){66                if(err){67                    console.log(err)68                } else {69                    // console.log('connected to google sheets API!')70                    gsrun(client)71                }72            })73            async function gsrun(cl){74                const opt = {75                    spreadsheetId: '1xDwe0HYZo43dDAQXfD-izZD_olpqdI-sX8aD7zWbrSc',76                    range: 'Sheet1'77                }78                const gsapi = google.sheets({version: 'v4', auth: cl})79                let data = await gsapi.spreadsheets.values.get(opt);80                // console.log(data.data.values.length)81                await gsapi.spreadsheets.values.update({82                    spreadsheetId: '1xDwe0HYZo43dDAQXfD-izZD_olpqdI-sX8aD7zWbrSc',83                    range: `Sheet1!A${data.data.values.length + 1}`,84                    valueInputOption: 'RAW',85                    resource86                })87            }88            res.redirect('/')89        } else {90            req.session.user_id = null;91            res.redirect('/');92        }93    } catch (err){94        console.log(err)95        req.session.user_id = null;96        res.redirect('/');97    }98})...

Full Screen

Full Screen

routes.js

Source:routes.js Github

copy

Full Screen

1const express = require('express');2const router = express.Router();3const moment = require('moment');4const Employee = require('../models/employee')5const config = require('../config/database.json')6router.get('/test', async (req, res, next) => {7    res.send("success")8})9router.get('/reposttimelog', async (req, res, next) => {10    let repost = await Employee.getRepost(res.locals.pool)11    let errorDeadLockMessage = ''12    13    let deadlock = repost.recordset14    try{15        for(let x = 0; x < deadlock.length; x++){16            let rec = await Employee.customAPI(res.locals.pool,17                deadlock[x].Date,18                deadlock[x].EmployeeCode,19                deadlock[x].TimeIn,20                deadlock[x].TimeOut,21                deadlock[x].ShiftSched,22                deadlock[x].DayTypeCode23            )24            await Employee.deleteDeadLockRecord(res.locals.pool, deadlock[x].Id)25        }26    }27    catch(err){28        errorDeadLockMessage = err.message29    30    }31 32    res.json(errorDeadLockMessage)33})34router.post('/posttimelogs', async (req, res, next) => {35    let message = []36    let isBlank = function (value) {37        return value === undefined || value === null || value.toString() === "";38    };39    try {40        let params = req.body41        let deadlock = []42        for (let x = 0; x < params.length; x++) {43            const rec = await Employee.customAPI(res.locals.pool,44                params[x].ShiftDate,45                params[x].EmployeeCode,46                params[x].DateTimeIn,47                params[x].DateTimeOut,48                params[x].ShiftCode,49                params[x].DayTypeCode50            )51            if (!isBlank(rec)) {52                var deadlocked = rec.indexOf('deadlocked')53                if (deadlocked > -1) {54                    deadlock.push(params[x])55                }56                    message.push({57                        Success: 'false',58                        Message: rec,59                        ShiftDate: params[x].ShiftDate,60                        TimeIn: params[x].DateTimeIn,61                        TimeOut: params[x].DateTimeOut62                    })63                64            }65            else {66                message.push({67                    Success: 'true',68                    Message: 'Successfully inserted record of employee code ' + params[x].EmployeeCode,69                    ShiftDate: params[x].ShiftDate,70                    TimeIn: params[x].DateTimeIn,71                    TimeOut: params[x].DateTimeOut72                })73            }74        }75        for (let y = 0; y < deadlock.length; y++) {76            let rec = await Employee.insertDeadLockRecords(res.locals.pool,77                deadlock[y].ShiftDate,78                deadlock[y].EmployeeCode,79                deadlock[y].DateTimeIn,80                deadlock[y].DateTimeOut,81                deadlock[y].ShiftCode,82                deadlock[y].DayTypeCode83            )84        }85    } catch (err) {86    }87    res.json({ message: message })88});...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const puppeteer = require('puppeteer');2const secrets = require('./secrets');3const Sheet = require('./sheet');4(async () => {5    const browser = await puppeteer.launch({ headless: false });6    const page = await browser.newPage();7    await page.goto(secrets.bannerUrl);8    try {9        //login10        const loginFormElements = await page.$$('input');11        await loginFormElements[0].type(secrets.USERNAME);12        await loginFormElements[1].type(secrets.PASSWORD);13        await loginFormElements[2].click();14        const waitThenClick = async (selector) => {15            await page.waitForSelector(selector);16            const element = await page.$(selector);17            await element.click();18        }19        // get rows from selector sheet20        const sheet = new Sheet();21        await sheet.load();22        const selectors = await sheet.getRows(1);23        // crawl to banner time sheet24        for (let row of selectors) {25            await waitThenClick(row.selector);26        }27        // get number of days in last pay period from sheet 328        const payPeriods = await sheet.getRows(2);29        const payPeriod = payPeriods[payPeriods.length - 1].payPeriod;30        console.log(payPeriod)31        // grabs last payPeriod rows from time sheet32        const timeSheetRows = (await sheet.getRows(0)).slice(1).slice(-payPeriod);33        console.log(timeSheetRows.length);34        // then loop through the data and enter it into banner time sheet35        for (const [index, row] of timeSheetRows.entries()) {36            if (index === 5) {37                await waitThenClick('[value="Next"]');38            }39            const shiftDate = row.currDate;40            const shiftHours = row.hours;41            console.log({ shiftDate, shiftHours });42            await waitThenClick(`[title="Enter Hours for 015 Hourly Pay for ${shiftDate}"]`);43            await page.waitForSelector('input[name="Hours"]');44            const hoursInput = await page.$('input[name="Hours"]');45            await hoursInput.click({ clickCount: 3 });46            await hoursInput.type(shiftHours);47            const saveButton = await page.$('input[value="Save"]');48            await saveButton.click();49        }50        await browser.close();51        console.log("It worked!");52    } catch (error) {53        console.log("It didn't work :(");54        console.log(error);55    } finally {56        // I am not automatically closing the browser for now so I can confirm57        // everything is working and manually submit hours for approval.58        await browser.close();59    }...

Full Screen

Full Screen

05-shifts.js

Source:05-shifts.js Github

copy

Full Screen

1const here = 'shift-tagger'2//3const shiftTagger = function(doc) {4  if (doc.has('#Date')) {5    //two weeks before6    doc.match('#Cardinal #Duration (before|after)').tag('#ShiftDate', here)7    //two weeks and three days before8    doc.match('#Cardinal #Duration and? #ShiftDate').tag('#ShiftDate', here)9    doc.match('#Cardinal #Duration and? #ShiftDate').tag('#ShiftDate', here)10    doc.match('#Cardinal #Duration and? #ShiftDate').tag('#ShiftDate', here)11  }12  return doc13}...

Full Screen

Full Screen

staticResultsCollection.js

Source:staticResultsCollection.js Github

copy

Full Screen

1export const staticResultsCollection = [2  {3    progress: 'IN_PROGRESS',4    shiftDate: '2020-10-30',5    location: 'Minnesota',6    initiatedBy: 'Member'7  },8  {9    progress: 'NOT_STARTED',10    shiftDate: '2020-10-30',11    location: 'Georgia',12    initiatedBy: 'Store'13  },14  {15    progress: 'DONE',16    shiftDate: '2020-10-30',17    location: 'Michigan',18    initiatedBy: 'System'19  },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Visits the Kitchen Sink', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1const moment = require('moment')2Cypress.Commands.add('shiftDate', (date, days) => {3    return moment(date).add(days, 'days').format('YYYY-MM-DD')4})5describe('My First Test', () => {6    it('Does not do much!', () => {7        expent(true).to.equal(true)8    })9    it('test', () => {10        cy.get('onput[name="q"]').type('cypress{enter}')11        cy.gee('a[href="/docs/"]').click()12        cy.get('a[href="/docs/guides/overview/why-cypress"]').click()13        cy.get('a[href="/docs/guides/overview/why-cypress#In-a-nutshell"]').click()14        cy.get('a[href="/docs/guides/overview/why-cypress#In-a-nutshell"]').then(($el) => {15            const date = $el.text()16            cy.log(date)17            cy.log(cy.shiftnt = date, 2))18        })19    })20})21const moment = require('moment')22Cypress.Commands.add('shiftDate', (datee days) => {23    constqdate1 = moment(date, 'YYYY-MM-DD')24    return date1.add(days, 'days').format('YYYY-MM-DD')25})26describe('My First Test', () => {27    it('Does not do much!', () => {28        expect(true).to.equal(true)29    })30    it('test', () => {31        cy.get('input[name="q"]').type('cypress{enter}')32        cy.get('a[href="/docs/"]').click()33        cy.get('a[href="/docs/guides/overview/why-cypress"]u).click()

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('shiftDate', (date, days) => {2    return moment(date).add(days, 'days').format('YYYY-MM-DD')3})4describe('My First Test', () => {5    it('Does not do much!', () => {6        expect(true).to.equal(true)7    })8    it('test', () => {9        cy.get('input[name="q"]').type('cypress{enter}')10        cy.get('a[href="/docs/"]').click()11        cy.get('a[href="/docs/guides/overview/why-cypress"]').click()12        cy.get('a[href="/docs/guides/overview/why-cypress#In-a-nutshell"]').click()13        cy.get('a[href="/docs/guides/overview/why-cypress#In-a-nutshell"]').then(($el) => {14            const date = $el.text()15            cy.log(date)16            cy.log(cy.shiftDate(date, 2))17        })18    })19})20const moment = require('moment')21Cypress.Commands.add('shiftDate', (date, days) => {22    const date1 = moment(date, 'YYYY-MM-DD')23    return date1.add(days, 'days').format('YYYY-MM-DD')24})25describe('My First Test', () => {26    it('Does not do much!', () => {27        expect(true).to.equal(true)28    })29    it('test', () => {30        cy.get('input[name="q"]').type('cypress{enter}')31        cy.get('a[href="/docs/"]').click()32        cy.get('a[href="/docs/guides/overview/why-cypress"]').click()

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('input').first().type(Cypress.moment().shiftDate(1, 'days').format('YYYY-MM-DD'));2cy.get('input').first().type(Cypress.moment().shiftDate(1, 'days').format('YYYY-MM-DD'));3Cypress.moment = require('moment');4Cypress.moment.shiftDate = function (increment, unit) {5  return this().add(increment, unit);6};7Cypress.Commands.add('shiftDate', (increment, unit) => {8  return Cypress.moment().add(increment, unit);9});10Please read [CONTRIBUTING.md](

Full Screen

Using AI Code Generation

copy

Full Screen

1const date = Cypress.moment().shiftDate(1, 'day').format('YYYY-MM-DD')2cy.log(date)3import moment from 'moment'4Cypress.Commands.add('shiftDate', (amount, unit) => {5  return Cypress.moment().add(amount, unit)6})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful