Przeglądarkowy hash!
This commit is contained in:
parent
8569fc5310
commit
cb770a73c0
|
|
@ -11,6 +11,7 @@ import { format, parse } from 'date-fns';
|
|||
import { createHash } from 'crypto';
|
||||
|
||||
|
||||
|
||||
class AssetLifeChangeWrapper {
|
||||
when = signal<string>(YearMonth.todayTxt());
|
||||
initial = signal<number>(0);
|
||||
|
|
@ -62,35 +63,36 @@ export class AssetCalculatorComponent {
|
|||
this.saveState(this.controlsToAsset());
|
||||
}
|
||||
|
||||
private restoreState() {
|
||||
private async restoreState() {
|
||||
const savedAsset = localStorage.getItem(STORAGE_KEY);
|
||||
const savedResults = localStorage.getItem(CACHE_KEY);
|
||||
const savedHash = localStorage.getItem(HASH_KEY);
|
||||
|
||||
|
||||
if (savedAsset) {
|
||||
const asset: Asset = JSON.parse(savedAsset);
|
||||
this.assetToControls(asset);
|
||||
|
||||
// Generujemy nowy hash
|
||||
const newHash = this.generateHash(asset);
|
||||
|
||||
// Jeśli hash jest taki sam, ładujemy wyniki z cache
|
||||
// 🛠️ Poczekaj na hash
|
||||
const newHash = await this.generateHash(asset);
|
||||
|
||||
if (savedHash === newHash && savedResults) {
|
||||
this.amortizationsSignal.set(JSON.parse(savedResults));
|
||||
console.log("✅ Załadowano wyniki z cache – brak przeliczeń.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
console.log("🔄 Hash zmieniony – wykonuję przeliczenie.");
|
||||
this.reCalculate();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private saveState(asset: Asset) {
|
||||
private async saveState(asset: Asset) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(asset));
|
||||
localStorage.setItem(HASH_KEY, this.generateHash(asset)); // Zapisujemy nowy hash
|
||||
const hash = await this.generateHash(asset);
|
||||
localStorage.setItem(HASH_KEY, hash);
|
||||
}
|
||||
|
||||
|
||||
private assetToControls(asset: Asset) {
|
||||
if (!asset.life.length) return;
|
||||
const [firstLife, ...restLives] = asset.life;
|
||||
|
|
@ -164,7 +166,8 @@ export class AssetCalculatorComponent {
|
|||
datepicker.close();
|
||||
}
|
||||
|
||||
private generateHash(asset: Asset): string {
|
||||
|
||||
private async generateHash(asset: Asset): Promise<string> {
|
||||
const data = JSON.stringify({
|
||||
initialValue: asset.life[0]?.initial,
|
||||
rate: asset.depreciationMethods[0]?.rate,
|
||||
|
|
@ -172,7 +175,14 @@ export class AssetCalculatorComponent {
|
|||
factor: asset.depreciationMethods[0]?.factor,
|
||||
lifeChanges: asset.life.map(lc => ({ when: lc.when, initial: lc.initial }))
|
||||
});
|
||||
|
||||
return createHash('sha256').update(data).digest('hex');
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const dataBuffer = encoder.encode(data);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
|
||||
|
||||
return Array.from(new Uint8Array(hashBuffer))
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue