55 lines
1.4 KiB
Go
55 lines
1.4 KiB
Go
|
|
package repository
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"database/sql"
|
||
|
|
"fmt"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/muyuqingfeng/iloom/auth-service/internal/model"
|
||
|
|
)
|
||
|
|
|
||
|
|
type NotificationRepo struct {
|
||
|
|
db *sql.DB
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewNotificationRepo(db *sql.DB) *NotificationRepo {
|
||
|
|
return &NotificationRepo{db: db}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (r *NotificationRepo) ListByRecipient(ctx context.Context, userID string) ([]model.Notification, error) {
|
||
|
|
query := `SELECT id, recipient_id, sender_id, sender_company_id, title, content, type, plan_id, is_read, read_at, created_at
|
||
|
|
FROM ilm_notification WHERE recipient_id = ? ORDER BY created_at DESC`
|
||
|
|
rows, err := r.db.QueryContext(ctx, query, userID)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("list notifications: %w", err)
|
||
|
|
}
|
||
|
|
defer rows.Close()
|
||
|
|
|
||
|
|
var notifications []model.Notification
|
||
|
|
for rows.Next() {
|
||
|
|
var n model.Notification
|
||
|
|
if err := rows.Scan(
|
||
|
|
&n.ID, &n.RecipientID, &n.SenderID, &n.SenderCompanyID,
|
||
|
|
&n.Title, &n.Content, &n.Type, &n.PlanID,
|
||
|
|
&n.IsRead, &n.ReadAt, &n.CreatedAt,
|
||
|
|
); err != nil {
|
||
|
|
return nil, fmt.Errorf("scan notification: %w", err)
|
||
|
|
}
|
||
|
|
notifications = append(notifications, n)
|
||
|
|
}
|
||
|
|
return notifications, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func (r *NotificationRepo) MarkRead(ctx context.Context, id, userID string) error {
|
||
|
|
now := time.Now()
|
||
|
|
_, err := r.db.ExecContext(ctx,
|
||
|
|
`UPDATE ilm_notification SET is_read = true, read_at = ? WHERE id = ? AND recipient_id = ?`,
|
||
|
|
now, id, userID,
|
||
|
|
)
|
||
|
|
if err != nil {
|
||
|
|
return fmt.Errorf("mark notification read: %w", err)
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|