Skip to content

Commit

Permalink
bugfix rework with moment js
Browse files Browse the repository at this point in the history
  • Loading branch information
OSousa117 committed Sep 14, 2023
1 parent afafa0e commit d580460
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,15 @@

package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities;

import java.time.LocalDateTime;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.time.LocalDate;
import java.util.UUID;

@Entity
@Table(name = "demand_series_values")
@Data
Expand All @@ -54,7 +48,7 @@ public class DemandSeriesValues {
private DemandSeries demandSeries;

@Column(name = "calendar_week", nullable = false)
private LocalDateTime calendarWeek;
private LocalDate calendarWeek;

@Column(name = "demand", nullable = false)
private Double demand;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,10 @@

package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.impl;

import eclipse.tractusx.demand_capacity_mgmt_specification.model.CompanyDto;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.DemandCategoryResponse;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.MaterialDemandRequest;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.MaterialDemandResponse;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.MaterialDemandSeries;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.MaterialDemandSeriesResponse;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.MaterialDemandSeriesValue;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.UnitMeasure;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import eclipse.tractusx.demand_capacity_mgmt_specification.model.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.CompanyEntity;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.DemandCategoryEntity;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.DemandSeries;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.DemandSeriesValues;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.MaterialDemandEntity;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.UnitMeasureEntity;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.*;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.MaterialDemandStatus;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.exceptions.BadRequestException;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.exceptions.NotFoundException;
Expand All @@ -55,6 +38,13 @@
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.utils.UUIDUtil;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RequiredArgsConstructor
@Service
@Slf4j
Expand Down Expand Up @@ -272,18 +262,18 @@ private DemandSeries enrichDemandSeries(

private List<DemandSeriesValues> enrichDemandSeriesValues(List<MaterialDemandSeriesValue> demandSeriesValues) {
return demandSeriesValues
.stream()
.map(
materialDemandSeriesValue ->
DemandSeriesValues
.builder()
.demand(materialDemandSeriesValue.getDemand().doubleValue())
.calendarWeek(
DataConverterUtil.convertFromString(materialDemandSeriesValue.getCalendarWeek().toString())
)
.build()
)
.toList();
.stream()
.map(
materialDemandSeriesValue ->
DemandSeriesValues
.builder()
.demand(materialDemandSeriesValue.getDemand().doubleValue())
.calendarWeek(
LocalDate.parse(materialDemandSeriesValue.getCalendarWeek())
)
.build()
)
.toList();
}

private MaterialDemandSeriesResponse enrichMaterialDemandSeriesResponse(DemandSeries demandSeries) {
Expand Down
70 changes: 36 additions & 34 deletions demand-capacity-mgmt-frontend/src/components/WeeklyView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,79 +26,79 @@ import { DemandCategoryContext } from '../contexts/DemandCategoryProvider';
import { Demand, DemandCategory, DemandProp, DemandSeriesValue, MaterialDemandSery } from '../interfaces/demand_interfaces';
import { Button, ButtonGroup, ToggleButton, OverlayTrigger, Tooltip } from 'react-bootstrap';
import { DemandContext } from '../contexts/DemandContextProvider';
import moment from 'moment';
import 'moment-weekday-calc';

import {getISOWeek, startOfMonth, addDays, format, addWeeks, addMonths, startOfWeek, setISODay} from 'date-fns';

import {getISOWeek, format,} from 'date-fns';

interface WeeklyViewProps {
demandData: DemandProp;
}

function getISOWeekMonday(year: number, isoWeek: number): Date {
const january1 = new Date(year, 0, 1);
const firstThursday = setISODay(january1, 4); // 4 corresponds to Thursday
return startOfWeek(addDays(firstThursday, (isoWeek - 1) * 7), { weekStartsOn: 1 }); // Starts on Monday
function getISOWeekMonday(year: number, isoWeek: number): moment.Moment {
return moment().year(year).isoWeek(isoWeek).startOf('isoWeek');
}

function getDateFromISOWeek(isoWeekString: string): Date {

function getDateFromISOWeek(isoWeekString: string): moment.Moment {
const [yearStr, weekStr] = isoWeekString.split('-W');
const year = parseInt(yearStr, 10);
const week = parseInt(weekStr, 10);
return getISOWeekMonday(year, week);
}

function getYearOfWeek(date: Date): number {
const thursday = addDays(date, 3 - (date.getUTCDay() + 6) % 7);
return thursday.getUTCFullYear();

function getYearOfWeek(date: moment.Moment): number {
return date.add(3, 'days').year();
}


function getWeeksInMonth(year: number, monthIndex: number, knownNextMonthWeeks?: Set<number>): number[] {
const weeks: Set<number> = new Set();

const firstDayOfMonth = new Date(year, monthIndex, 1);
const lastDayOfMonth = new Date(year, monthIndex + 1, 0);
const nextMonth = new Date(year, monthIndex + 1, 1);

const firstDayOfMonth = moment().year(year).month(monthIndex).startOf('month');
const lastDayOfMonth = moment().year(year).month(monthIndex).endOf('month');
// Fetch weeks of the next month if not provided.
if (!knownNextMonthWeeks && monthIndex < 11) {
knownNextMonthWeeks = new Set(getWeeksInMonth(year, monthIndex + 1));
}

let currentDay = firstDayOfMonth;
while (currentDay <= lastDayOfMonth) {
const weekNum = getISOWeek(currentDay);
const weekNum = currentDay.week();
const isoWeekYear = getYearOfWeek(currentDay);

// If the month is January and the week year is the previous year, skip it
if (monthIndex === 0 && isoWeekYear < year) {
currentDay = addDays(currentDay, 1);
currentDay = currentDay.add(1, 'days');
continue;
}

// If it's the last week of the month and it's also in the next month, skip it.
if (currentDay > new Date(year, monthIndex, 24) && knownNextMonthWeeks?.has(weekNum)) {
currentDay = addDays(currentDay, 1);
if (currentDay.isAfter(moment(new Date(year, monthIndex, 24))) && knownNextMonthWeeks?.has(weekNum)) {
currentDay = currentDay.add(1, 'days');
continue;
}

weeks.add(weekNum);
currentDay = addDays(currentDay, 1);
currentDay = currentDay.add(1, 'days');
}

return Array.from(weeks).sort((a, b) => a - b);
}



const WeeklyView: React.FC<WeeklyViewProps> = ({ demandData }) => {
const { updateDemand } = useContext(DemandContext)!;
const { demandcategories } = useContext(DemandCategoryContext) || {};
const { demandcategories } = useContext(DemandCategoryContext) ?? {};
const currentYear = new Date().getFullYear();

const [editMode, setEditMode] = useState(false);

const monthsPreviousYear = Array.from({ length: 1 }, (_, monthIndex) => {
const monthStart = new Date(currentYear - 1, monthIndex + 11, 1);
const monthName = format(monthStart, 'MMM');
const monthName = format(monthStart, 'MMM'); // <-- This line
let weeks = getWeeksInMonth(currentYear - 1, monthIndex + 11);
return {
name: monthName,
Expand Down Expand Up @@ -150,28 +150,32 @@ const WeeklyView: React.FC<WeeklyViewProps> = ({ demandData }) => {
}

// Function to get the beginning and end dates of the week
const getWeekDates = (year: number, month: string,week: number) => {
const getWeekDates = (year: number, month: string, week: number) => {
const startDate = getISOWeekMonday(year, week);

const endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + 6); // Assuming weeks end on Saturdays
const endDate = startDate.clone().add(6, 'days'); // Instead of using native Date() methods

return {
startDate: startDate.toDateString(),
endDate: endDate.toDateString(),
startDate: startDate.format('YYYY-MM-DD'),
endDate: endDate.format('YYYY-MM-DD'),
};
};




useEffect(() => {
console.log("aqui")
const newDemandValuesMap: DemandValuesMap = {};

demandData.demandSeries?.forEach((series) => {
const categoryId = series.demandCategory.id;

series.demandSeriesValues.forEach((value) => {
const date = getDateFromISOWeek(value.calendarWeek);
const year = date.getFullYear();
const week = getISOWeek(date).toString();
const date = moment(value.calendarWeek);
const year = moment().year();
const week = date.week();
console.log(week);

if (!newDemandValuesMap[categoryId]) {
newDemandValuesMap[categoryId] = {};
Expand Down Expand Up @@ -202,11 +206,12 @@ const WeeklyView: React.FC<WeeklyViewProps> = ({ demandData }) => {
monthsCurrentYear.forEach((month) => {
month.weeks.forEach((week) => {
const isoWeekMonday = getISOWeekMonday(month.year, week);
isoWeekMonday.format('YYYY-MM-dd')
// Get the Monday of the ISO week
const demand = demandValuesMap[categoryId]?.[month.year]?.[week];
if (demand !== undefined) {
demandSeriesValues.push({
calendarWeek: format(isoWeekMonday, 'yyyy-MM-dd'),
calendarWeek: isoWeekMonday.format('YYYY-MM-DD'),
demand: demand,
});
}
Expand Down Expand Up @@ -373,10 +378,7 @@ const WeeklyView: React.FC<WeeklyViewProps> = ({ demandData }) => {
))
)}
</tr>

{demandcategories &&
demandcategories
.sort((a, b) => a.id.localeCompare(b.id))
{demandcategories?.sort((a, b) => a.id.localeCompare(b.id))
.map((category: DemandCategory) => (
<tr key={category.id}>
<th className="sticky-header-cell">
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"dependencies": {
"moment": "^2.29.4",
"moment-weekday-calc": "^1.1.4"
}
}
13 changes: 13 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


moment-weekday-calc@^1.1.4:
version "1.1.4"
resolved "https://registry.yarnpkg.com/moment-weekday-calc/-/moment-weekday-calc-1.1.4.tgz#ebf57d4c9cf1446e330c207658aa0a90816d4dc9"
integrity sha512-/Gyrgu9pQnapt47wPmp/Fk0h+Qx0QJyf9uwBtu4bLINzAoraDOVN2cprUiBzcTMOuFroW2V0y9yJTJ71UUV6Xg==

moment@^2.29.4:
version "2.29.4"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.4.tgz#3dbe052889fe7c1b2ed966fcb3a77328964ef108"
integrity sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==

0 comments on commit d580460

Please sign in to comment.