Files
king 7f94e5efe7 feat(프로젝트): 매일 하는 업무 — 날짜 팝업 [매일]·반복 아이콘·시각별 알림
- 마이그레이션 033 tasks.repeat_daily — [매일]이면 마감일·시각 비움, 마감일을 고르면 꺼짐(미적용이면 버튼 숨김·PUT 503)
- 마감 칸(카드·목록·내 업무·세부 업무·업무 창)에 반복 아이콘 + "매일"
- reminders.run_daily_alerts: 영업일, Project 옵션 daily_alert_times 중 지난 가장 늦은 시각마다 담당자(없으면 협업자)에게 type=daily 알림(task_reminders 로 중복 방지, 데몬 1분 주기)
- 큰 알림 팝업·PC 알림 프로그램에서 매일 업무 줄은 노란 배경
- Project 옵션 "알림" 분류: 알림 시각 여러 개 추가·삭제(최대 12)
- 도움말·모듈 CLAUDE.md·DEPLOYMENT(033) 갱신, 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:35:59 +09:00

168 lines
7.7 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace DbxNotifier
{
internal sealed class Alert
{
public long Id;
public string Type = "";
public string Title = "";
public string Body = "";
public string Actor = "";
public long TaskId;
public long ProjectId;
public bool IsMention => Type == "mention";
public bool IsDaily => Type == "daily"; // 매일 하는 업무(project_db 033) — 줄 배경을 따로
/// <summary>제목 앞 "나를 태그함: " / "업무 배정: "(예전 알림은 "작업 배정: ") 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
public string CleanTitle
{
get
{
foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:", "매일 업무:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title;
}
}
/// <summary>둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게).</summary>
public string SubLine
{
get
{
string who = Actor;
int at = who.IndexOf('@');
if (at > 0) who = who.Substring(0, at);
if (who.Length > 0) who = char.ToUpperInvariant(who[0]) + who.Substring(1);
if (Body.Length > 0 && who.Length > 0) return Body + " · " + who;
return Body.Length > 0 ? Body : who;
}
}
// 작업 알림은 공유 링크(/project/t/{id}) — 서버가 지금 권한으로 열 수 있는 프로젝트(연결된 프로젝트 포함)로
// 보낸다. 원 소속 주소로 열면 연결된 프로젝트에서만 읽을 수 있는 사람에게 403 이 났다.
public string Path => TaskId > 0
? "/project/t/" + TaskId
: ProjectId > 0 ? "/project/p/" + ProjectId : "/project/inbox";
}
internal sealed class AlertResult
{
public string Name = "";
public long LatestId;
public List<Alert> Alerts = new List<Alert>();
}
internal sealed class ApiException : Exception
{
public readonly int Status;
public ApiException(int status, string message) : base(message) { Status = status; }
}
/// <summary>ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다.</summary>
internal sealed class Api : IDisposable
{
private readonly HttpClient _http;
private static readonly JavaScriptSerializer Json = new JavaScriptSerializer();
public Api()
{
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("DBXNotifier/" + typeof(Api).Assembly.GetName().Version.ToString(3));
}
public void Dispose() => _http.Dispose();
/// <summary>서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외).</summary>
public static string NormalizeServer(string raw)
{
string s = (raw ?? "").Trim().TrimEnd('/');
if (!Uri.TryCreate(s, UriKind.Absolute, out Uri u) || (u.AbsolutePath != "/" && u.AbsolutePath.Length > 0))
throw new ArgumentException("ERP 주소가 올바르지 않습니다. 예: " + Settings.DefaultServer);
bool local = u.Host == "localhost" || u.Host == "127.0.0.1";
if (u.Scheme != Uri.UriSchemeHttps && !(local && u.Scheme == Uri.UriSchemeHttp))
throw new ArgumentException("ERP 주소는 https:// 로 시작해야 합니다.");
return u.GetLeftPart(UriPartial.Authority);
}
private async Task<Dictionary<string, object>> Send(HttpMethod method, string url, string token, object body)
{
using (var req = new HttpRequestMessage(method, url))
{
if (!string.IsNullOrEmpty(token)) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body != null) req.Content = new StringContent(Json.Serialize(body), Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await _http.SendAsync(req).ConfigureAwait(false))
{
string text = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
Dictionary<string, object> d = null;
try { d = Json.Deserialize<Dictionary<string, object>>(text); } catch { /* HTML 오류 화면 등 */ }
if (!res.IsSuccessStatusCode)
{
string detail = d != null && d.TryGetValue("detail", out var x) ? x as string : null;
throw new ApiException((int)res.StatusCode, detail ?? ("서버 오류 HTTP " + (int)res.StatusCode));
}
return d ?? new Dictionary<string, object>();
}
}
}
private static string Str(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : "";
private static long Num(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToInt64(v) : 0;
public async Task<(string Code, string Poll, string ApprovePath, int ExpiresIn)> StartLink(string server, string device)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/start", null, new { device }).ConfigureAwait(false);
return (Str(d, "code"), Str(d, "poll"), Str(d, "approve_path"), (int)Num(d, "expires_in"));
}
/// <summary>연결 확인 — status: pending | expired | ok(token, email).</summary>
public async Task<(string Status, string Token, string Email)> PollLink(string server, string poll)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/poll", null, new { poll }).ConfigureAwait(false);
return (Str(d, "status"), Str(d, "token"), Str(d, "email"));
}
public async Task<AlertResult> Alerts(string server, string token, long after)
{
var d = await Send(HttpMethod.Get, server + "/project/api/notifier/alerts?after=" + after, token, null).ConfigureAwait(false);
var r = new AlertResult { Name = Str(d, "name"), LatestId = Num(d, "latest_id") };
if (d.TryGetValue("alerts", out var list) && list is IEnumerable items)
{
foreach (object o in items)
{
if (!(o is Dictionary<string, object> a)) continue;
r.Alerts.Add(new Alert
{
Id = Num(a, "id"),
Type = Str(a, "type"),
Title = Str(a, "title"),
Body = Str(a, "body"),
Actor = Str(a, "actor_email"),
TaskId = Num(a, "task_id"),
ProjectId = Num(a, "project_id"),
});
}
}
return r;
}
public Task MarkRead(string server, string token, long id) =>
Send(HttpMethod.Post, server + "/project/api/notifier/alerts/" + id + "/read", token, new { });
public Task Logout(string server, string token) =>
Send(HttpMethod.Post, server + "/project/api/notifier/logout", token, new { });
}
}