@deenruv/order-reminder-plugin 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ # License 1
2
+
3
+ The MIT License
4
+
5
+ Copyright (c) 2025-present Aexol
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12
+
13
+ # License 2
14
+
15
+ The MIT License
16
+
17
+ Copyright (c) 2018-2025 Michael Bromley
18
+
19
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # @deenruv/order-reminder-plugin
2
+
3
+ Plugin that sends reminder events for orders that have been in a specific state for a configurable duration. It supports multiple reminder rules, each targeting a specific order state and age threshold, and publishes custom Deenruv events that can trigger email notifications or other actions.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @deenruv/order-reminder-plugin
9
+ ```
10
+
11
+ ## Configuration
12
+
13
+ ```typescript
14
+ import { OrderReminderPlugin } from '@deenruv/order-reminder-plugin';
15
+ import { MyPaymentReminderEvent } from './events';
16
+
17
+ // In your Deenruv server config:
18
+ plugins: [
19
+ OrderReminderPlugin.init([
20
+ {
21
+ uniqueId: 'payment-reminder-24h',
22
+ orderState: 'ArrangingPayment',
23
+ orderAgeMs: 24 * 60 * 60 * 1000, // 24 hours
24
+ eventCtor: MyPaymentReminderEvent,
25
+ batchSize: 50,
26
+ orderFrom: new Date('2025-01-01'),
27
+ },
28
+ ]),
29
+ ]
30
+ ```
31
+
32
+ ## Features
33
+
34
+ - Configurable reminder rules with order state and age thresholds
35
+ - Publishes custom Deenruv events for each qualifying order (integrates with email/notification systems)
36
+ - Per-rule tracking to prevent duplicate reminder sends
37
+ - Batch processing with configurable batch sizes
38
+ - Optional `orderFrom` date to avoid spamming historical orders when enabling the plugin
39
+ - Supports multiple independent reminder rules
40
+
41
+ ## Admin UI
42
+
43
+ This plugin is server-only and does not add any admin UI extensions.
44
+
45
+ ## API Extensions
46
+
47
+ This plugin does not add any GraphQL API extensions. It operates via a controller endpoint and internal event publishing.
@@ -0,0 +1 @@
1
+ export declare const ORDER_REMINDMER_PLUGIN_OPTIONS: unique symbol;
@@ -0,0 +1 @@
1
+ export const ORDER_REMINDMER_PLUGIN_OPTIONS = Symbol("ORDER_REMINDMER_PLUGIN_OPTIONS");
@@ -0,0 +1,8 @@
1
+ import type { Response } from "express";
2
+ import { RequestContext } from "@deenruv/core";
3
+ import { OrderReminderService } from "../services/order-reminder.service.js";
4
+ export declare class OrderReminderController {
5
+ private service;
6
+ constructor(service: OrderReminderService);
7
+ run(ctx: RequestContext, res: Response): Promise<void>;
8
+ }
@@ -0,0 +1,39 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Controller, Get, HttpStatus, Res } from "@nestjs/common";
14
+ import { Allow, Ctx, Permission, RequestContext } from "@deenruv/core";
15
+ import { OrderReminderService } from "../services/order-reminder.service.js";
16
+ let OrderReminderController = class OrderReminderController {
17
+ service;
18
+ constructor(service) {
19
+ this.service = service;
20
+ }
21
+ async run(ctx, res) {
22
+ const result = await this.service.run(ctx);
23
+ res.status(HttpStatus.OK).json({ status: "OK", ...result });
24
+ }
25
+ };
26
+ __decorate([
27
+ Allow(Permission.UpdateOrder),
28
+ Get(""),
29
+ __param(0, Ctx()),
30
+ __param(1, Res()),
31
+ __metadata("design:type", Function),
32
+ __metadata("design:paramtypes", [RequestContext, Object]),
33
+ __metadata("design:returntype", Promise)
34
+ ], OrderReminderController.prototype, "run", null);
35
+ OrderReminderController = __decorate([
36
+ Controller("order-reminder"),
37
+ __metadata("design:paramtypes", [OrderReminderService])
38
+ ], OrderReminderController);
39
+ export { OrderReminderController };
@@ -0,0 +1,7 @@
1
+ import { DeepPartial } from "typeorm";
2
+ import { DeenruvEntity, Order } from "@deenruv/core";
3
+ export declare class OrderReminderEntity extends DeenruvEntity {
4
+ constructor(input?: DeepPartial<OrderReminderEntity>);
5
+ order: Order;
6
+ remindmerSend: Record<string, boolean>;
7
+ }
@@ -0,0 +1,35 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Column, Entity, Index, ManyToOne, Unique } from "typeorm";
11
+ import { DeenruvEntity, Order } from "@deenruv/core";
12
+ let OrderReminderEntity = class OrderReminderEntity extends DeenruvEntity {
13
+ constructor(input) {
14
+ super(input);
15
+ }
16
+ order;
17
+ remindmerSend;
18
+ };
19
+ __decorate([
20
+ ManyToOne(() => Order, { eager: true, onDelete: "CASCADE" }),
21
+ __metadata("design:type", Order)
22
+ ], OrderReminderEntity.prototype, "order", void 0);
23
+ __decorate([
24
+ Column({ type: "jsonb", default: {} }),
25
+ __metadata("design:type", Object)
26
+ ], OrderReminderEntity.prototype, "remindmerSend", void 0);
27
+ OrderReminderEntity = __decorate([
28
+ Entity(),
29
+ Unique(["order"]) // one reminder per order
30
+ ,
31
+ Index(["order"]) // used in join/filter; JSON key checks are handled in query
32
+ ,
33
+ __metadata("design:paramtypes", [Object])
34
+ ], OrderReminderEntity);
35
+ export { OrderReminderEntity };
@@ -0,0 +1,6 @@
1
+ import { OrderRemindmerPluginOptions } from "./types.js";
2
+ declare class OrderReminderPlugin {
3
+ private static options;
4
+ static init(options: OrderRemindmerPluginOptions): typeof OrderReminderPlugin;
5
+ }
6
+ export { OrderReminderPlugin };
@@ -0,0 +1,34 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { PluginCommonModule, DeenruvPlugin } from "@deenruv/core";
8
+ import { OrderReminderController } from "./controllers/order-reminder.controller.js";
9
+ import { OrderReminderService } from "./services/order-reminder.service.js";
10
+ import { ORDER_REMINDMER_PLUGIN_OPTIONS } from "./constants.js";
11
+ import { OrderReminderEntity } from "./entities/order-reminder.entity.js";
12
+ let OrderReminderPlugin = class OrderReminderPlugin {
13
+ static options;
14
+ static init(options) {
15
+ this.options = options;
16
+ return this;
17
+ }
18
+ };
19
+ OrderReminderPlugin = __decorate([
20
+ DeenruvPlugin({
21
+ compatibility: "^0.0.40",
22
+ imports: [PluginCommonModule],
23
+ entities: [OrderReminderEntity],
24
+ controllers: [OrderReminderController],
25
+ providers: [
26
+ {
27
+ provide: ORDER_REMINDMER_PLUGIN_OPTIONS,
28
+ useFactory: () => OrderReminderPlugin.options,
29
+ },
30
+ OrderReminderService,
31
+ ],
32
+ })
33
+ ], OrderReminderPlugin);
34
+ export { OrderReminderPlugin };
@@ -0,0 +1,11 @@
1
+ import { TransactionalConnection, RequestContext, EventBus } from "@deenruv/core";
2
+ import { OrderRemindmerPluginOptions } from "../types.js";
3
+ export declare class OrderReminderService {
4
+ private connection;
5
+ private eventBus;
6
+ private options;
7
+ constructor(connection: TransactionalConnection, eventBus: EventBus, options: OrderRemindmerPluginOptions);
8
+ run(ctx: RequestContext): Promise<{
9
+ processed: number;
10
+ }>;
11
+ }
@@ -0,0 +1,135 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Inject, Injectable } from "@nestjs/common";
14
+ import { TransactionalConnection, EventBus, Order, } from "@deenruv/core";
15
+ import { ORDER_REMINDMER_PLUGIN_OPTIONS } from "../constants.js";
16
+ import { OrderReminderEntity } from "../entities/order-reminder.entity.js";
17
+ import { In } from "typeorm";
18
+ let OrderReminderService = class OrderReminderService {
19
+ connection;
20
+ eventBus;
21
+ options;
22
+ constructor(connection, eventBus, options) {
23
+ this.connection = connection;
24
+ this.eventBus = eventBus;
25
+ this.options = options;
26
+ }
27
+ async run(ctx) {
28
+ const orderRepo = this.connection.getRepository(ctx, Order);
29
+ const reminderRepo = this.connection.getRepository(ctx, OrderReminderEntity);
30
+ let processed = 0;
31
+ const rules = Array.isArray(this.options)
32
+ ? this.options
33
+ : [];
34
+ for (const rule of rules) {
35
+ const threshold = new Date(Date.now() - rule.orderAgeMs);
36
+ const batchSize = rule.batchSize ?? 100;
37
+ let fetched = 0;
38
+ let lastUpdatedAt;
39
+ let lastId;
40
+ while (true) {
41
+ // Use NOT EXISTS to exclude orders already reminded for this rule
42
+ let qb = orderRepo
43
+ .createQueryBuilder("o")
44
+ .leftJoinAndSelect("o.customer", "c")
45
+ .leftJoinAndSelect("o.lines", "lines")
46
+ .where("o.updatedAt < :threshold", { threshold })
47
+ .andWhere("o.state = :state", { state: rule.orderState })
48
+ .andWhere('o."customerId" IS NOT NULL')
49
+ .andWhere("lines.id IS NOT NULL")
50
+ .andWhere(`NOT EXISTS (
51
+ SELECT 1 FROM ${orderRepo.metadata.schema
52
+ ? '"' + orderRepo.metadata.schema + '".'
53
+ : ""}"${reminderRepo.metadata.tableName}" rem
54
+ WHERE rem."orderId" = o.id
55
+ AND coalesce(rem."remindmerSend" ->> :key, 'false') = 'true'
56
+ )`, { key: rule.uniqueId });
57
+ if (rule.orderFrom) {
58
+ qb = qb.andWhere("o.createdAt >= :orderFrom", {
59
+ orderFrom: rule.orderFrom,
60
+ });
61
+ }
62
+ if (lastUpdatedAt) {
63
+ qb = qb.andWhere("(o.updatedAt > :lastUpdatedAt OR (o.updatedAt = :lastUpdatedAt AND o.id > :lastId))", { lastUpdatedAt, lastId });
64
+ }
65
+ const oldOrders = await qb
66
+ .orderBy("o.updatedAt", "ASC")
67
+ .addOrderBy("o.id", "ASC")
68
+ .take(batchSize)
69
+ .getMany();
70
+ fetched = oldOrders.length;
71
+ if (fetched === 0)
72
+ break;
73
+ const ids = oldOrders.map((o) => o.id);
74
+ const reminders = await reminderRepo.find({
75
+ where: { order: { id: In(ids) } },
76
+ relations: { order: true },
77
+ });
78
+ const remByOrderId = new Map();
79
+ for (const r of reminders)
80
+ remByOrderId.set(r.order.id, r);
81
+ for (const order of oldOrders) {
82
+ let reminder = remByOrderId.get(order.id) ?? null;
83
+ if (!reminder) {
84
+ try {
85
+ reminder = reminderRepo.create({
86
+ order,
87
+ remindmerSend: { [rule.uniqueId]: false },
88
+ });
89
+ reminder = await reminderRepo.save(reminder);
90
+ remByOrderId.set(order.id, reminder);
91
+ }
92
+ catch {
93
+ // Unique race: fetch existing
94
+ reminder = await reminderRepo.findOne({
95
+ where: { order: { id: order.id } },
96
+ relations: { order: true },
97
+ });
98
+ if (!reminder)
99
+ continue;
100
+ }
101
+ }
102
+ if (reminder.remindmerSend?.[rule.uniqueId]) {
103
+ lastUpdatedAt = order.updatedAt;
104
+ lastId = order.id;
105
+ continue;
106
+ }
107
+ try {
108
+ const EventCtor = rule.eventCtor;
109
+ const eventInstance = new EventCtor(ctx, order);
110
+ await this.eventBus.publish(eventInstance);
111
+ reminder.remindmerSend = {
112
+ ...(reminder.remindmerSend ?? {}),
113
+ [rule.uniqueId]: true,
114
+ };
115
+ await reminderRepo.save(reminder);
116
+ processed++;
117
+ }
118
+ catch {
119
+ // Swallow individual order errors
120
+ }
121
+ lastUpdatedAt = order.updatedAt;
122
+ lastId = order.id;
123
+ }
124
+ }
125
+ }
126
+ return { processed };
127
+ }
128
+ };
129
+ OrderReminderService = __decorate([
130
+ Injectable(),
131
+ __param(2, Inject(ORDER_REMINDMER_PLUGIN_OPTIONS)),
132
+ __metadata("design:paramtypes", [TransactionalConnection,
133
+ EventBus, Array])
134
+ ], OrderReminderService);
135
+ export { OrderReminderService };