Skip to content

Commit

Permalink
Merge pull request #40 from ra4nd0m/feature-addrecord-improv
Browse files Browse the repository at this point in the history
Feature addrecord improv
  • Loading branch information
ra4nd0m authored Aug 31, 2024
2 parents cfbc875 + 63cb464 commit afeac82
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 89 deletions.
167 changes: 87 additions & 80 deletions src/pages/components/AddRecord.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,51 @@
import "flatpickr/dist/flatpickr.css";
import * as Sentry from "@sentry/svelte";
import RecordsDisplay from "./RecordsDisplay.svelte";
import { onMount } from "svelte";
export let mat_id: number;
export let secret: string;
let created_on: string | any;
let minPrice: string | number;
let maxPrice: number | string;
let avgPrice: number | string;
//Works only when prop ids are static
//Better to utilise backend functionality
let propValuePairs: propValuePair[] = [];
let isPropsFetched = false;
function calculateAvgPrice() {
if (typeof minPrice != "undefined" && typeof maxPrice != "undefined") {
avgPrice = (Number(minPrice) + Number(maxPrice)) / 2;
}
}
async function submitRecord() {
//Works only when prop ids are static
//Better to utilise backend functionality
let alertMessage = "";
if (created_on === "") alertMessage += "Дата не задана!\n";
let propList: matProp[] = [];
onMount(async () => {
let payload = JSON.stringify({ material_source_id: `${mat_id}` });
propList =
(await doFetch(payload, "/getPropertyList", secret).then((val) => {
if (typeof val === "object" && "list" in val) {
return val.list as matProp[];
}
})) || [];
propList.forEach((prop) => {
if (prop.Name !== "") {
propValuePairs.push({ propName: prop.Name });
}
});
isPropsFetched = true;
});
if (typeof minPrice === "undefined" || minPrice === "")
alertMessage += "Минимальная цена не задана!\n";
if (typeof maxPrice === "undefined" || maxPrice === "")
alertMessage += "Максимальная цена не задана!\n";
if (alertMessage !== "") {
alert(alertMessage);
async function submitRecord() {
if (created_on === "") {
alert("Дата не задана!");
return;
}
let payloadAvgPrice = {
material_source_id: mat_id,
property_name: "Средняя цена",
value_float: `${avgPrice}`,
value_str: `${avgPrice}`,
created_on: created_on,
};
let payloadMinPrice = {
material_source_id: mat_id,
property_name: "Мин цена",
value_float: `${minPrice}`,
value_str: `${minPrice}`,
created_on: created_on,
};
let payloadMaxPrice = {
material_source_id: mat_id,
property_name: "Макс цена",
value_float: `${maxPrice}`,
value_str: `${maxPrice}`,
created_on: created_on,
};
try {
await Promise.all([
await addRecord(JSON.stringify(payloadAvgPrice)),
await addRecord(JSON.stringify(payloadMinPrice)),
await addRecord(JSON.stringify(payloadMaxPrice)),
]);
} catch (err) {
Sentry.captureException(err);
alert(err);
for (const propPair of propValuePairs) {
if (propPair.propValue !== undefined && propPair.propValue !== "") {
const payload = {
material_source_id: mat_id,
property_name: `${propPair.propName}`,
value_float: `${propPair.propValue}`,
value_str: `${propPair.propValue}`,
created_on: created_on,
};
try {
await addRecord(JSON.stringify(payload));
} catch (err) {
Sentry.captureException(err);
alert(err);
}
}
}
}
async function addRecord(payload: string) {
Expand All @@ -72,6 +58,43 @@
}
return;
}
$: {
if (isPropsFetched) {
const minPriceIndex = propValuePairs.findIndex(
(pair) => pair.propName === "Мин цена",
);
const maxPriceIndex = propValuePairs.findIndex(
(pair) => pair.propName === "Макс цена",
);
if (
minPriceIndex !== -1 &&
maxPriceIndex !== -1 &&
propValuePairs[minPriceIndex].propValue !== undefined &&
propValuePairs[maxPriceIndex].propValue !== undefined
) {
const avgPrice =
(Number(propValuePairs[minPriceIndex].propValue) +
Number(propValuePairs[maxPriceIndex].propValue)) /
2;
const avgPriceIndex = propValuePairs.findIndex(
(pair) => pair.propName === "Средняя цена",
);
if (avgPriceIndex !== -1) {
if (avgPrice === 0) {
propValuePairs[avgPriceIndex].propValue = "";
} else {
propValuePairs[avgPriceIndex].propValue = avgPrice;
}
}
}
}
}
interface propValuePair {
propName: string;
propValue?: string | number;
}
</script>

<RecordsDisplay {mat_id} {secret} bShowLastRecords={true} />
Expand All @@ -81,34 +104,18 @@
await submitRecord();
}}
>
<div class="ms-3 mt-3">
<input
type="text"
class="form-control"
placeholder="Мин цена"
bind:value={minPrice}
on:input={() => calculateAvgPrice()}
/>
</div>
<div class="ms-3 mt-3">
<input
type="text"
class="form-control"
placeholder="Макс цена"
bind:value={maxPrice}
on:input={() => calculateAvgPrice()}
/>
</div>
<div class="ms-3 mt-3">
<input
type="text"
class="form-control"
placeholder="Средняя цена"
bind:value={avgPrice}
disabled
/>
</div>

{#if isPropsFetched}
{#each propValuePairs as propPair}
<div class="ms-3 mt-3">
<input
type="text"
class="form-control"
placeholder={propPair.propName}
bind:value={propPair.propValue}
/>
</div>
{/each}
{/if}
<div class="ms-3 mt-3">
<Flatpickr
options={{ enableTime: false }}
Expand Down
18 changes: 12 additions & 6 deletions src/pages/components/GetMaterialProps.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
onMount(async () => {
let payload = JSON.stringify({ material_source_id: `${mat_id}` });
let result = await doFetch(payload, "/getPropertyList", secret);
if (typeof result === "object" && "list" in result && result.list !== null) {
if (
typeof result === "object" &&
"list" in result &&
result.list !== null
) {
material_props_list = result.list as matProp[];
} else {
material_props_list = [];
Expand Down Expand Up @@ -45,11 +49,13 @@
</thead>
<tbody>
{#each material_props_list as row}
<tr>
<td>{row.Id}</td>
<td>{row.Name}</td>
<td>{row.Kind}</td>
</tr>
{#if row.Id <= 6 || import.meta.env.VITE_DEBUG === "true"}
<tr>
<td>{row.Id}</td>
<td>{row.Name}</td>
<td>{row.Kind}</td>
</tr>
{/if}
{/each}
<tr>
<td />
Expand Down
1 change: 0 additions & 1 deletion src/pages/components/GetMaterialsList.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import { materials_data } from "../lib/stores";
import { onMount } from "svelte";
export let secret: string;
let bigList: material[];
onMount(async () => {
await grabData(secret);
});
Expand Down
11 changes: 9 additions & 2 deletions src/pages/components/RecordsDisplay.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
if (prop.Id > 6 || prop.Id < 1) {
continue;
}
//If prop is not selected skip
if (!prop.isSelected) {
continue;
}
Expand Down Expand Up @@ -110,6 +111,7 @@
// Add the value array to the initialData array
initialData.push(value);
}
//If avg values selected do the same thing
if (isAvgChecked) {
isFetchAttempted = true;
let payloadAvg = {
Expand All @@ -133,6 +135,7 @@
const buf = item.date.split("T");
item.date = buf[0];
});
//Add avg dates to the initialData array
initialData.push(valuesAvg);
}
// Create a new array of unique dates from the initialData array
Expand All @@ -151,6 +154,7 @@
recivedDates.sort(
(a, b) => new Date(a).getTime() - new Date(b).getTime(),
);
//Create maReachedIndex to calculate the amount of valueX properties created in dataList array
let maxReachedIndex = 0;
// Map over each date in recivedDates to create a new object for each date
// Each object contains the date and the corresponding values from the initialData array
Expand All @@ -163,16 +167,19 @@
initialData.forEach((arr, index) => {
// Find the object in the array that has the same date as the current item
let valObj = arr.find((obj) => obj.date === item);
// If an object with the same date is found, add its value to the new object
// Otherwise, add an empty string
//Check if new index+1 which equals to X in valueX is bigger then previous max index+1
//If it is so, then we have new biggest valueX
if (index + 1 > maxReachedIndex) {
maxReachedIndex = index + 1;
}
// If an object with the same date is found, add its value to the new object
// Otherwise, add an empty string
object[`value${index + 1}`] = valObj ? valObj.value : "";
});
// Return the new object as an item in the dataList array
return object as dataListToDisplay;
});
//Create an empty array with length of maxReachedIndex to interate over when table is being rendered
maxIndexArr = Array.from({ length: maxReachedIndex });
}
Expand Down

0 comments on commit afeac82

Please sign in to comment.