Procházet zdrojové kódy

0210348-备忘录、账户数据库

0210348 před 2 měsíci
rodič
revize
09bc5ac266

+ 2 - 10
src/app/child-page/bounty-store/bounty-store.page.html

@@ -1,7 +1,7 @@
 <ion-header>
   <ion-toolbar>
     <ion-buttons slot="start">
-      <ion-back-button defaultHref="/tabs/tab3"></ion-back-button>
+      <ion-back-button defaultHref="/tabs/mine"></ion-back-button>
     </ion-buttons>
     <ion-title>赏金商店</ion-title>
   </ion-toolbar>
@@ -47,13 +47,5 @@
         <ion-card-title>其他</ion-card-title>
       </ion-card-header>
     </ion-card>
-    
-    <!-- <ion-card (click)="openPopup('其他')">
-      <ion-card-header>
-        <ion-icon name="ellipsis-horizontal" color="dark"></ion-icon>
-        <ion-card-title>其他</ion-card-title>
-      </ion-card-header>
-    </ion-card> -->
-    
   </div>
-</ion-content>
+</ion-content>

+ 100 - 10
src/app/child-page/bounty-store/bounty-store.page.ts

@@ -1,18 +1,88 @@
-import { Component } from '@angular/core';
+import { Component, OnInit } from '@angular/core';
 import { AlertController } from '@ionic/angular';
+import * as Parse from 'parse';
 
 @Component({
   selector: 'app-bounty-store',
   templateUrl: 'bounty-store.page.html',
   styleUrls: ['bounty-store.page.scss']
 })
-export class BountyStorePage {
-
-  currentBounty: number = 100;
-  totalSpent: number = 50;
+export class BountyStorePage implements OnInit {
+  currentBounty: number = 1000; // 初始化账户余额
+  totalSpent: number = 0; // 初始化累计支出
+  username: string = ''; // 当前用户的用户名
+  historyId: number = 1; // 初始化historyId
+  expenseRecord: number = 0; // 初始化expenseRecord
 
   constructor(private alertController: AlertController) {}
 
+  async ngOnInit() {
+    //检测登录状况
+    this.loadUserData();
+    //刷新数据
+    this.loadAccountData();
+  }
+
+  ionViewDidEnter() {
+    //检测登录状况
+    this.loadUserData();
+    //刷新数据
+    this.loadAccountData();
+  }
+
+  async loadUserData() {
+    const currentUser = Parse.User.current();
+    if (currentUser) {
+      this.username = currentUser.getUsername()!;
+    } else {
+      this.username = '未登录';
+    }
+  }
+
+  async loadAccountData() {
+    try {
+      const query = new Parse.Query('account_history');
+      query.equalTo('username', this.username);
+      query.ascending('historyId');
+      const accountHistory = await query.find();
+
+      if (accountHistory.length > 0) {
+        const latestHistory = accountHistory[accountHistory.length - 1];
+        this.currentBounty = latestHistory.get('account');
+        this.historyId = latestHistory.get('historyId') + 1;
+
+        this.totalSpent = accountHistory
+          .filter(history => history.get('type') === 'expense')
+          .reduce((total, history) => total + history.get('amount'), 0);
+        
+        this.expenseRecord = this.totalSpent; // 初始化expenseRecord为累计支出
+      } else {
+        await this.createInitialAccount();
+      }
+    } catch (error) {
+      console.error('Error loading account data', error);
+    }
+  }
+
+  async createInitialAccount() {
+    const AccountHistory = Parse.Object.extend('account_history');
+    const accountHistory = new AccountHistory();
+
+    accountHistory.set('username', this.username);
+    accountHistory.set('amount', 1000);
+    accountHistory.set('type', 'initial');
+    accountHistory.set('remark', '初始账户');
+    accountHistory.set('account', 1000);
+    accountHistory.set('historyId', 1);
+    accountHistory.set('expenseRecord', 0); // 初始化expenseRecord为0
+
+    try {
+      await accountHistory.save();
+    } catch (error) {
+      console.error('Error creating initial account', error);
+    }
+  }
+
   async openPopup(activity: string) {
     const alert = await this.alertController.create({
       header: '消费详情',
@@ -35,12 +105,10 @@ export class BountyStorePage {
         },
         {
           text: '确认',
-          handler: (data: any) => {
-            // 处理确认消费的逻辑,更新赏金余额和消费记录
+          handler: async (data: any) => {
             const amount = parseFloat(data.amount);
             if (!isNaN(amount) && amount > 0) {
-              this.currentBounty -= amount;
-              this.totalSpent += amount;
+              await this.updateAccountHistory(amount, data.note);
             }
           }
         }
@@ -50,4 +118,26 @@ export class BountyStorePage {
     await alert.present();
   }
 
-}
+  async updateAccountHistory(amount: number, note: string) {
+    const AccountHistory = Parse.Object.extend('account_history');
+    const accountHistory = new AccountHistory();
+
+    accountHistory.set('username', this.username);
+    accountHistory.set('amount', amount);
+    accountHistory.set('type', 'expense');
+    accountHistory.set('remark', note);
+    accountHistory.set('account', this.currentBounty - amount);
+    accountHistory.set('historyId', this.historyId);
+    accountHistory.set('expenseRecord', this.expenseRecord + amount); // 更新expenseRecord
+
+    try {
+      await accountHistory.save();
+      this.currentBounty -= amount;
+      this.totalSpent += amount;
+      this.expenseRecord += amount; // 更新本地的expenseRecord
+      this.historyId += 1; // Increment historyId for the next entry
+    } catch (error) {
+      console.error('Error updating account history', error);
+    }
+  }
+}

+ 5 - 1
src/app/home/home.page.html

@@ -8,8 +8,12 @@
     </ion-toolbar>
   </ion-header>
     
+  <div *ngIf="taskCompleted" class="task-completed-message">
+    恭喜你完成减重任务,获得了赏金!
+  </div>
+
   <!-- 方框 -->
-  <ion-card (click)="openEditModal()">
+  <ion-card (click)="openEditModal()" class="weight-card">
     <ion-card-content>
       <ion-grid>
         <ion-row>

+ 17 - 2
src/app/home/home.page.scss

@@ -1,7 +1,22 @@
 ion-searchbar {
   --background: #f4f4f4;
-  margin: 10px;
-  border-radius: 10px;
+  margin-top: 20px;
+  margin-bottom: 10px;
+  border-radius: 0px;
+}
+
+/* 保持其他元素的布局 */
+.weight-card {
+  margin-top: 40px; /* 调整这个值以确保有足够的空间 */
+}
+
+
+.task-completed-message{
+  position:fixed;
+  text-align: center;
+  font-weight: bold;
+  font-size: 18px;
+  margin-left: 18%;
 }
 
 .info-box {

+ 43 - 5
src/app/home/home.page.ts

@@ -1,4 +1,4 @@
-import { Component, OnInit, OnDestroy } from '@angular/core';
+import { Component, OnInit } from '@angular/core';
 import { AlertController, NavController } from '@ionic/angular';
 import { Router } from '@angular/router';
 import * as Parse from 'parse';
@@ -15,7 +15,8 @@ export class HomePage implements OnInit {
   reward: number = 0;
   username: string = ''; // 当前用户的用户名
   blueColor: boolean = false;
-  
+  taskCompleted: boolean = false; // 任务完成标志
+
   constructor(
     private alertController: AlertController,
     private router: Router,
@@ -30,8 +31,6 @@ export class HomePage implements OnInit {
     this.loadUserData();
   }
 
-  ngOnDestroy() {}
-
   async loadUserData() {
     const currentUser = Parse.User.current();
     if (currentUser) {
@@ -54,6 +53,15 @@ export class HomePage implements OnInit {
         this.current = weightStatus.get('current') || 0;
         this.target = weightStatus.get('target') || 0;
         this.reward = this.calculateReward(this.initial, this.target);
+
+        // 检查任务是否完成
+        if (this.current === this.target && this.initial !== this.target) {
+          await this.completeTask(weightStatus);
+        } else if (this.current === this.initial && this.current === this.target) {
+          this.taskCompleted = true; // 设置任务完成标志
+        } else {
+          this.taskCompleted = false; // 重置任务完成标志
+        }
       } else {
         // 没有找到用户数据时,将所有体重数据重置为0
         this.initial = 0;
@@ -70,7 +78,37 @@ export class HomePage implements OnInit {
       this.reward = 0;
     }
   }
-  
+
+  async completeTask(weightStatus: Parse.Object) {
+    // 更新 weight_status 数据库中的初始体重和目标体重
+    weightStatus.set('initial', this.current);
+    weightStatus.set('target', this.current);
+    await weightStatus.save();
+
+    // 记录完成任务的赏金到 account_history 数据库
+    const AccountHistory = Parse.Object.extend('account_history');
+    const accountHistory = new AccountHistory();
+
+    const historyQuery = new Parse.Query('account_history');
+    historyQuery.equalTo('username', this.username);
+    const latestHistory = await historyQuery.descending('historyId').first();
+    const historyId = latestHistory ? latestHistory.get('historyId') + 1 : 1;
+    const currentBounty = latestHistory ? latestHistory.get('account') : 1000;
+    const rewardAmount = this.calculateReward(this.initial, this.target);
+
+    accountHistory.set('username', this.username);
+    accountHistory.set('amount', rewardAmount);
+    accountHistory.set('type', 'income');
+    accountHistory.set('remark', '完成任务');
+    accountHistory.set('account', currentBounty + rewardAmount);
+    accountHistory.set('historyId', historyId);
+    accountHistory.set('expenseRecord', latestHistory ? latestHistory.get('expenseRecord') : 0); // 保留现有的支出记录
+
+    await accountHistory.save();
+    await this.loadUserData();
+    // 显示任务完成消息
+    this.taskCompleted = true;
+  }
 
   calculateReward(initial: number, target: number): number {
     return (initial - target) * 10;

+ 2 - 0
src/app/memo/memo.page.html

@@ -26,6 +26,7 @@
     <ion-title>备忘录</ion-title>
   </ion-toolbar>
 </ion-header>
+
 <ion-content>
 
   <div *ngIf="segment === 'memo'">
@@ -47,3 +48,4 @@
     </ion-item>
   </div>
 </ion-content>
+

+ 95 - 93
src/app/memo/memo.page.ts

@@ -1,77 +1,10 @@
-// import { Component, OnInit } from '@angular/core';
-// import { AlertController } from '@ionic/angular';
-// @Component({
-//   selector: 'app-memo',
-//   templateUrl: './memo.page.html',
-//   styleUrls: ['./memo.page.scss'],
-// })
-// export class MemoPage implements OnInit {
-//   segment: string = 'memo';
-//   memos: string[] = [];
-//   newMemo: string = '';
-//   newMessage: string = '';
-//   constructor(private alertController: AlertController) {}
-//   ngOnInit() {
-//     this.loadMemos();
-//   }
-//   //加载备忘录
-//   loadMemos() {
-//     const memos = localStorage.getItem('memos');
-//     if (memos) {
-//       this.memos = JSON.parse(memos);
-//     }
-//   }
-//   //保存备忘录
-//   saveMemos() {
-//     localStorage.setItem('memos', JSON.stringify(this.memos));
-//   }
-//   //异步函数,添加备忘录
-//   async addMemo() {
-//     if (this.newMemo.trim().length > 0) {
-//       this.memos.push(this.newMemo);
-//       this.newMemo = '';
-//       this.saveMemos();
-//       const alert = await this.alertController.create({
-//         header: '提示',
-//         message: '添加成功',
-//         buttons: ['确定']
-//       });
-//       await alert.present();
-//     }
-//   }
-//   //异步函数,确认删除
-//   async confirmDeleteMemo(memo: string) {
-//     const alert = await this.alertController.create({
-//       header: '确认删除',
-//       message: `你确定要删除 "${memo}" 吗?`,
-//       buttons: [
-//         {
-//           text: '取消',
-//           role: 'cancel'
-//         },
-//         {
-//           text: '删除',
-//           handler: () => {
-//             this.memos = this.memos.filter(m => m !== memo);
-//             this.saveMemos();
-//           }
-//         }
-//       ]
-//     });
-//     await alert.present();
-//   }
-//   //删除备忘录
-//   deleteMemo(memo: string) {
-//     this.memos = this.memos.filter(m => m !== memo);
-//     this.saveMemos();
-//   }
-// }
-
-
 import { Component, OnInit } from '@angular/core';
 import { AlertController } from '@ionic/angular';
+import * as Parse from 'parse';
 
 interface Memo {
+  memoId: number;
+  username: string;
   content: string;
   timestamp: Date;
 }
@@ -85,39 +18,97 @@ export class MemoPage implements OnInit {
   segment: string = 'memo';
   memos: Memo[] = [];
   newMemo: string = '';
+  username: string = ''; // Current user's username
+  nextMemoId: number = 1; // Track next memoId for the current user
 
   constructor(private alertController: AlertController) {}
 
   ngOnInit() {
-    this.loadMemos();
+    const currentUser = Parse.User.current();
+    if (currentUser) {
+      this.username = currentUser.getUsername()!;
+      this.loadMemos();
+      this.loadNextMemoId(); // Load the next memoId for the current user
+    } else {
+      console.error('User not logged in.');
+    }
   }
 
-  loadMemos() {
-    const memos = localStorage.getItem('memos');
-    if (memos) {
-      this.memos = JSON.parse(memos);
+  ionViewDidEnter() {
+    const currentUser = Parse.User.current();
+    if (currentUser) {
+      this.username = currentUser.getUsername()!;
+      this.loadMemos();
+      this.loadNextMemoId(); // Load the next memoId for the current user
+    } else {
+      console.error('User not logged in.');
     }
   }
 
-  saveMemos() {
-    localStorage.setItem('memos', JSON.stringify(this.memos));
+  async loadNextMemoId() {
+    try {
+      const query = new Parse.Query('memo_history');
+      query.equalTo('username', this.username);
+      query.descending('memoId');
+      query.limit(1); // Limit to the last memo to get the highest memoId
+      const result = await query.first();
+
+      if (result) {
+        this.nextMemoId = result.get('memoId') + 1;
+      } else {
+        this.nextMemoId = 1; // Initialize to 1 if no memos exist for the user
+      }
+    } catch (error) {
+      console.error('Error loading next memoId', error);
+    }
+  }
+
+  async loadMemos() {
+    try {
+      const query = new Parse.Query('memo_history');
+      query.equalTo('username', this.username);
+      query.descending('createdAt');
+      query.limit(3); // Limit to latest three memos
+      const results = await query.find();
+
+      this.memos = results.map((memo: any) => ({
+        memoId: memo.get('memoId'),
+        username: memo.get('username'),
+        content: memo.get('content'),
+        timestamp: memo.get('time'),
+      }));
+
+    } catch (error) {
+      console.error('Error loading memos', error);
+    }
   }
 
   async addMemo() {
     if (this.newMemo.trim().length > 0) {
-      const newMemoObj: Memo = {
-        content: this.newMemo,
-        timestamp: new Date(),
-      };
-      this.memos.push(newMemoObj);
-      this.newMemo = '';
-      this.saveMemos();
-      const alert = await this.alertController.create({
-        header: '提示',
-        message: '添加成功',
-        buttons: ['确定']
-      });
-      await alert.present();
+      const MemoClass = Parse.Object.extend('memo_history');
+      const memo = new MemoClass();
+
+      memo.set('username', this.username);
+      memo.set('memoId', this.nextMemoId); // Assign the next available memoId
+      memo.set('content', this.newMemo);
+      memo.set('time', new Date());
+
+      try {
+        await memo.save();
+        this.loadMemos(); // Reload memos after adding a new one
+        this.newMemo = '';
+        this.nextMemoId++; // Increment the next memoId for future memos
+
+        const alert = await this.alertController.create({
+          header: '提示',
+          message: '添加成功',
+          buttons: ['确定']
+        });
+        await alert.present();
+
+      } catch (error) {
+        console.error('Error saving memo', error);
+      }
     }
   }
 
@@ -141,8 +132,19 @@ export class MemoPage implements OnInit {
     await alert.present();
   }
 
-  deleteMemo(memo: Memo) {
-    this.memos = this.memos.filter(m => m !== memo);
-    this.saveMemos();
+  async deleteMemo(memo: Memo) {
+    const MemoClass = Parse.Object.extend('memo_history');
+    const query = new Parse.Query(MemoClass);
+    query.equalTo('memoId', memo.memoId);
+    
+    try {
+      const result = await query.first();
+      if (result) {
+        await result.destroy();
+        this.loadMemos(); // Reload memos after deleting one
+      }
+    } catch (error) {
+      console.error('Error deleting memo', error);
+    }
   }
 }