agrs-sequelize-sdk 1.1.18 → 1.1.19
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/models/KeywordPerformance.js +42 -14
- package/package.json +1 -1
|
@@ -63,21 +63,49 @@ module.exports = (sequelize, DataTypes) => {
|
|
|
63
63
|
],
|
|
64
64
|
hooks: {
|
|
65
65
|
beforeCreate: async (record, options) => {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
66
|
+
try {
|
|
67
|
+
// Find the earliest date for this keyword using raw query for better performance
|
|
68
|
+
const [result] = await sequelize.query(
|
|
69
|
+
`
|
|
70
|
+
SELECT MIN("Date") as first_date
|
|
71
|
+
FROM "KeywordPerformance"
|
|
72
|
+
WHERE LOWER("Keyword") = LOWER(:keyword)
|
|
73
|
+
`,
|
|
74
|
+
{
|
|
75
|
+
replacements: { keyword: record.Keyword },
|
|
76
|
+
type: sequelize.QueryTypes.SELECT,
|
|
77
|
+
transaction: options.transaction,
|
|
78
|
+
}
|
|
79
|
+
);
|
|
78
80
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
+
// If no existing record found, use current record's date
|
|
82
|
+
// Otherwise, use the earlier date between existing and current
|
|
83
|
+
const existingFirstDate = result?.first_date;
|
|
84
|
+
record.FirstAppearanceDate = existingFirstDate
|
|
85
|
+
? Math.min(new Date(existingFirstDate), new Date(record.Date))
|
|
86
|
+
: record.Date;
|
|
87
|
+
|
|
88
|
+
// If we found an earlier date, update all existing records for this keyword
|
|
89
|
+
if (existingFirstDate && record.Date < existingFirstDate) {
|
|
90
|
+
await sequelize.query(
|
|
91
|
+
`
|
|
92
|
+
UPDATE "KeywordPerformance"
|
|
93
|
+
SET "FirstAppearanceDate" = :newDate
|
|
94
|
+
WHERE LOWER("Keyword") = LOWER(:keyword)
|
|
95
|
+
`,
|
|
96
|
+
{
|
|
97
|
+
replacements: {
|
|
98
|
+
newDate: record.Date,
|
|
99
|
+
keyword: record.Keyword,
|
|
100
|
+
},
|
|
101
|
+
transaction: options.transaction,
|
|
102
|
+
}
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
} catch (error) {
|
|
106
|
+
console.error("Error in FirstAppearanceDate hook:", error);
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
81
109
|
},
|
|
82
110
|
},
|
|
83
111
|
}
|