diff --git a/src/medications/medications.service.ts b/src/medications/medications.service.ts index 7936a48..4de26b5 100644 --- a/src/medications/medications.service.ts +++ b/src/medications/medications.service.ts @@ -171,9 +171,11 @@ export class MedicationsService { await this.deleteTodayUntakenRecords(medication); } - // 如果更新了服药时间,更新当天相关的未服用记录 + // 如果更新了服药时间,删除当天的记录,让系统重新生成新的记录 + // 这样更简单可靠,与激活状态更新的处理逻辑保持一致 if (updateDto.medicationTimes) { - await this.updateTodayUntakenRecords(medication, updateDto.medicationTimes); + await this.deleteTodayUntakenRecords(medication); + this.logger.log(`已删除药物 ${id} 当天的记录,系统会根据新的服药时间重新生成`); } this.logger.log(`成功更新药物 ${id}`); @@ -253,75 +255,6 @@ export class MedicationsService { return medication; } - /** - * 更新当天相关的未服用记录 - * 当药物的服药时间被更新时,将当天未服用的记录更新为新的服药时间 - */ - private async updateTodayUntakenRecords( - medication: Medication, - newMedicationTimes: string[], - ): Promise { - const today = dayjs().format('YYYY-MM-DD'); - const todayStart = dayjs(today).startOf('day').toDate(); - const todayEnd = dayjs(today).endOf('day').toDate(); - - this.logger.log( - `开始更新药物 ${medication.id} 在 ${today} 的未服用记录`, - ); - - // 查询当天该药物的未服用记录(状态为 UPCOMING) - const recordsToUpdate = await this.recordModel.findAll({ - where: { - medicationId: medication.id, - userId: medication.userId, - status: MedicationStatusEnum.UPCOMING, - scheduledTime: { - [Op.between]: [todayStart, todayEnd], - }, - deleted: false, - }, - }); - - if (recordsToUpdate.length === 0) { - this.logger.log(`没有找到 ${medication.id} 需要更新的记录`); - return; - } - - // 排序记录,按计划时间升序 - recordsToUpdate.sort((a, b) => { - const timeA = dayjs(a.scheduledTime).format('HH:mm'); - const timeB = dayjs(b.scheduledTime).format('HH:mm'); - return timeA.localeCompare(timeB); - }); - - // 更新记录的计划时间 - for (let i = 0; i < recordsToUpdate.length && i < newMedicationTimes.length; i++) { - const record = recordsToUpdate[i]; - const newTime = newMedicationTimes[i]; - - // 解析新的时间字符串(HH:mm) - const [hours, minutes] = newTime.split(':').map(Number); - - // 重新计算计划服药时间(基于今天) - const newScheduledTime = dayjs(today) - .hour(hours) - .minute(minutes) - .second(0) - .millisecond(0) - .toDate(); - - record.scheduledTime = newScheduledTime; - await record.save(); - - this.logger.log( - `更新记录 ${record.id} 的时间从 ${dayjs(record.scheduledTime).format('HH:mm')} 到 ${newTime}`, - ); - } - - this.logger.log( - `成功更新了 ${recordsToUpdate.length} 条 ${medication.id} 的当天记录`, - ); - } /** * 删除当天的药物记录 * 当药物被停用时,删除当天生成的所有记录