import { z, g as createDocument, s as saveToFile, l as loadFromFile, e as loadFromInput, f as saveToFileHandle, h as hashKey, c as createReducer, i as isBaseAction, a as createAction, B as BaseDocument, b as applyMixins, d as BaseActions } from './object-04f14c5c.js';
import 'json-stringify-deterministic';
import 'immer';
import 'crypto';
import 'fs';
import 'https';
import 'path';

// node_modules/@acaldas/document-model-graphql/dist/index-fe999334.js
var g = (e) => e != null;
var y = z.any().refine((e) => g(e));
var d = z.enum(["ADD_ACCOUNT"]);
var b = z.enum(["ADD_AUDIT_REPORT"]);
var f = z.enum(["ADD_COMMENT"]);
var _ = z.enum(["ADD_LINE_ITEM"]);
var A = z.enum(["ADD_VESTING"]);
function i() {
  return z.object({
    __typename: z.literal("Account").optional(),
    address: z.string(),
    lineItems: z.array(l()),
    name: z.string()
  });
}
function j() {
  return z.object({
    address: z.string(),
    lineItems: z.array(z.lazy(() => h())).nullish(),
    name: z.string().nullish()
  });
}
function I() {
  return z.object({
    address: z.string(),
    lineItems: z.array(l()).nullish(),
    name: z.string().nullish()
  });
}
function E() {
  return z.object({
    input: z.lazy(() => D()),
    type: d
  });
}
function D() {
  return z.object({
    accounts: z.array(z.lazy(() => j()))
  });
}
function T() {
  return z.object({
    attachments: z.array(z.lazy(() => et())),
    input: z.lazy(() => z2()),
    type: b
  });
}
function z2() {
  return z.object({
    reports: z.array(n())
  });
}
function C() {
  return z.object({
    input: z.lazy(() => L()),
    type: f
  });
}
function L() {
  return z.object({
    comments: z.array(z.lazy(() => P()))
  });
}
function O() {
  return z.object({
    input: z.lazy(() => U()),
    type: _
  });
}
function U() {
  return z.object({
    account: z.string(),
    lineItems: z.array(z.lazy(() => h()))
  });
}
function N() {
  return z.object({
    input: z.lazy(() => R()),
    type: A
  });
}
function R() {
  return z.object({
    vesting: z.array(z.lazy(() => Gt()))
  });
}
function n() {
  return z.object({
    __typename: z.literal("AuditReport").optional(),
    report: z.string(),
    status: v,
    timestamp: z.string().datetime()
  });
}
var v = z.enum(["Approved", "ApprovedWithComments", "Escalated", "NeedsAction"]);
function qt() {
  return z.object({
    __typename: z.literal("BudgetStatement").optional(),
    created: z.string().datetime(),
    data: M(),
    documentType: z.string(),
    lastModified: z.string().datetime(),
    name: z.string(),
    operations: z.array(y),
    revision: z.number()
  });
}
function Wt() {
  return z.union([E(), T(), C(), O(), N(), q(), H(), J(), X(), $(), jt(), It(), Et(), Dt(), Tt(), Ct(), Mt(), Vt(), wt(), Bt()]);
}
function M() {
  return z.object({
    __typename: z.literal("BudgetStatementData").optional(),
    accounts: z.array(i()),
    auditReports: z.array(n()),
    comments: z.array(a()),
    ftes: c().nullable(),
    month: z.string().nullable(),
    owner: p().nullable(),
    quoteCurrency: z.string().nullable(),
    vesting: z.array(S())
  });
}
function F() {
  return z.object({
    accounts: z.array(i()).nullish(),
    auditReports: z.array(n()).nullish(),
    comments: z.array(a()).nullish(),
    ftes: c().nullish(),
    month: z.string().nullish(),
    owner: p().nullish(),
    quoteCurrency: z.string().nullish(),
    vesting: z.array(S()).nullish()
  });
}
function Ht() {
  return z.object({
    created: z.string().datetime().nullish(),
    data: z.lazy(() => F()),
    documentType: z.string().nullish(),
    lastModified: z.string().datetime().nullish(),
    name: z.string().nullish(),
    revision: z.number().nullish()
  });
}
var r = z.enum(["Draft", "Escalated", "Final", "Review"]);
function a() {
  return z.object({
    __typename: z.literal("Comment").optional(),
    author: V(),
    comment: z.string(),
    key: z.string(),
    status: r,
    timestamp: z.string().datetime()
  });
}
function V() {
  return z.object({
    __typename: z.literal("CommentAuthor").optional(),
    id: z.string().nullable(),
    ref: z.string().nullable(),
    roleLabel: z.string().nullable(),
    username: z.string().nullable()
  });
}
function o() {
  return z.object({
    id: z.string().nullish(),
    ref: z.string().nullish(),
    roleLabel: z.string().nullish(),
    username: z.string().nullish()
  });
}
function P() {
  return z.object({
    author: z.lazy(() => o().nullish()),
    comment: z.string(),
    key: z.string().nullish(),
    status: r.nullish(),
    timestamp: z.string().datetime().nullish()
  });
}
function w() {
  return z.object({
    author: z.lazy(() => o().nullish()),
    comment: z.string().nullish(),
    key: z.string(),
    status: r.nullish(),
    timestamp: z.string().datetime().nullish()
  });
}
var x = z.enum(["DELETE_ACCOUNT"]);
var B = z.enum(["DELETE_AUDIT_REPORT"]);
var k = z.enum(["DELETE_COMMENT"]);
var G = z.enum(["DELETE_LINE_ITEM"]);
var Q = z.enum(["DELETE_VESTING"]);
function q() {
  return z.object({
    input: z.lazy(() => W()),
    type: x
  });
}
function W() {
  return z.object({
    accounts: z.array(z.string())
  });
}
function H() {
  return z.object({
    input: z.lazy(() => Y()),
    type: B
  });
}
function Y() {
  return z.object({
    reports: z.array(z.string())
  });
}
function J() {
  return z.object({
    input: z.lazy(() => K()),
    type: k
  });
}
function K() {
  return z.object({
    comments: z.array(z.string())
  });
}
function X() {
  return z.object({
    input: z.lazy(() => Z()),
    type: G
  });
}
function Z() {
  return z.object({
    account: z.string(),
    lineItems: z.array(z.lazy(() => at()))
  });
}
function $() {
  return z.object({
    input: z.lazy(() => tt()),
    type: Q
  });
}
function tt() {
  return z.object({
    vesting: z.array(z.string())
  });
}
function et() {
  return z.object({
    data: z.string(),
    extension: z.string().nullish(),
    fileName: z.string().nullish(),
    hash: z.string(),
    mimeType: z.string()
  });
}
function c() {
  return z.object({
    __typename: z.literal("Ftes").optional(),
    forecast: z.array(nt()),
    value: z.number()
  });
}
function nt() {
  return z.object({
    __typename: z.literal("FtesForecast").optional(),
    month: z.string(),
    value: z.number()
  });
}
function rt() {
  return z.object({
    month: z.string(),
    value: z.number()
  });
}
function ut() {
  return z.object({
    forecast: z.array(z.lazy(() => rt())),
    value: z.number()
  });
}
var it = z.enum(["LOAD_STATE"]);
function l() {
  return z.object({
    __typename: z.literal("LineItem").optional(),
    actual: z.number().nullable(),
    budgetCap: z.number().nullable(),
    category: m().nullable(),
    comment: z.string().nullable(),
    forecast: z.array(u()),
    group: s().nullable(),
    headcountExpense: z.boolean(),
    payment: z.number().nullable()
  });
}
function m() {
  return z.object({
    __typename: z.literal("LineItemCategory").optional(),
    id: z.string(),
    ref: z.string(),
    title: z.string()
  });
}
function at() {
  return z.object({
    category: z.string().nullish(),
    group: z.string().nullish()
  });
}
function u() {
  return z.object({
    __typename: z.literal("LineItemForecast").optional(),
    budgetCap: z.number(),
    month: z.string(),
    value: z.number()
  });
}
function s() {
  return z.object({
    __typename: z.literal("LineItemGroup").optional(),
    color: z.string(),
    id: z.string(),
    ref: z.string(),
    title: z.string()
  });
}
function h() {
  return z.object({
    actual: z.number().nullish(),
    budgetCap: z.number().nullish(),
    category: m().nullish(),
    comment: z.string().nullish(),
    forecast: z.array(u()).nullish(),
    group: s().nullish(),
    headcountExpense: z.boolean().nullish(),
    payment: z.number().nullish()
  });
}
function ot() {
  return z.object({
    actual: z.number().nullish(),
    budgetCap: z.number().nullish(),
    category: z.string().nullish(),
    comment: z.string().nullish(),
    forecast: z.array(u()).nullish(),
    group: z.string().nullish(),
    headcountExpense: z.boolean().nullish(),
    payment: z.number().nullish()
  });
}
function ct() {
  return z.object({
    category: z.string().nullish(),
    group: z.string().nullish()
  });
}
function Yt() {
  return z.object({
    input: z.lazy(() => lt()),
    type: it
  });
}
function lt() {
  return z.object({
    operations: z.number(),
    state: z.lazy(() => mt())
  });
}
function mt() {
  return z.object({
    data: z.unknown().nullish(),
    name: z.string()
  });
}
function Jt() {
  return z.object({
    __typename: z.literal("Operation").optional(),
    hash: z.string(),
    index: z.number(),
    timestamp: z.string().datetime(),
    type: z.string()
  });
}
function p() {
  return z.object({
    __typename: z.literal("Owner").optional(),
    id: z.string().nullable(),
    ref: z.string().nullable(),
    title: z.string().nullable()
  });
}
function st() {
  return z.object({
    id: z.string().nullish(),
    ref: z.string().nullish(),
    title: z.string().nullish()
  });
}
var ht = z.enum(["PRUNE"]);
function Kt() {
  return z.object({
    input: z.lazy(() => pt()),
    type: ht
  });
}
function pt() {
  return z.object({
    end: z.number().nullish(),
    start: z.number().nullish()
  });
}
var St = z.enum(["REDO"]);
function Xt() {
  return z.object({
    input: z.number(),
    type: St
  });
}
var gt = z.enum(["SET_FTES"]);
var yt = z.enum(["SET_MONTH"]);
var dt = z.enum(["SET_NAME"]);
var bt = z.enum(["SET_OWNER"]);
var ft = z.enum(["SET_QUOTE_CURRENCY"]);
var _t = z.enum(["SORT_ACCOUNTS"]);
var At = z.enum(["SORT_LINE_ITEMS"]);
function jt() {
  return z.object({
    input: z.lazy(() => ut()),
    type: gt
  });
}
function It() {
  return z.object({
    input: z.string(),
    type: yt
  });
}
function Zt() {
  return z.object({
    input: z.string(),
    type: dt
  });
}
function $t() {
  return z.object({
    __typename: z.literal("SetNameOperation").optional(),
    hash: z.string(),
    index: z.number(),
    input: z.string(),
    timestamp: z.string().datetime(),
    type: z.string()
  });
}
function Et() {
  return z.object({
    input: z.lazy(() => st()),
    type: bt
  });
}
function Dt() {
  return z.object({
    input: z.string(),
    type: ft
  });
}
function Tt() {
  return z.object({
    input: z.lazy(() => zt()),
    type: _t
  });
}
function zt() {
  return z.object({
    accounts: z.array(z.string())
  });
}
function Ct() {
  return z.object({
    input: z.lazy(() => Lt()),
    type: At
  });
}
function Lt() {
  return z.object({
    account: z.string(),
    lineItems: z.array(z.lazy(() => ct()))
  });
}
var Ot = z.enum(["UNDO"]);
var Ut = z.enum(["UPDATE_ACCOUNT"]);
var Nt = z.enum(["UPDATE_COMMENT"]);
var Rt = z.enum(["UPDATE_LINE_ITEM"]);
var vt = z.enum(["UPDATE_VESTING"]);
function te() {
  return z.object({
    input: z.number(),
    type: Ot
  });
}
function Mt() {
  return z.object({
    input: z.lazy(() => Ft()),
    type: Ut
  });
}
function Ft() {
  return z.object({
    accounts: z.array(z.lazy(() => I()))
  });
}
function Vt() {
  return z.object({
    input: z.lazy(() => Pt()),
    type: Nt
  });
}
function Pt() {
  return z.object({
    comments: z.array(z.lazy(() => w()))
  });
}
function wt() {
  return z.object({
    input: z.lazy(() => xt()),
    type: Rt
  });
}
function xt() {
  return z.object({
    account: z.string(),
    lineItems: z.array(z.lazy(() => ot()))
  });
}
function Bt() {
  return z.object({
    input: z.lazy(() => kt()),
    type: vt
  });
}
function kt() {
  return z.object({
    vesting: z.array(z.lazy(() => Qt()))
  });
}
function S() {
  return z.object({
    __typename: z.literal("Vesting").optional(),
    amount: z.string(),
    amountOld: z.string(),
    comment: z.string(),
    currency: z.string(),
    date: z.string(),
    key: z.string(),
    vested: z.boolean()
  });
}
function Gt() {
  return z.object({
    amount: z.string().nullish(),
    amountOld: z.string().nullish(),
    comment: z.string().nullish(),
    currency: z.string().nullish(),
    date: z.string().nullish(),
    key: z.string().nullish(),
    vested: z.boolean().nullish()
  });
}
function Qt() {
  return z.object({
    amount: z.string().nullish(),
    amountOld: z.string().nullish(),
    comment: z.string().nullish(),
    currency: z.string().nullish(),
    date: z.string().nullish(),
    key: z.string(),
    vested: z.boolean().nullish()
  });
}
var ee = Object.freeze(Object.defineProperty({
  __proto__: null,
  AccountInputSchema: j,
  AccountSchema: i,
  AccountUpdateInputSchema: I,
  AddAccountActionSchema: E,
  AddAccountInputSchema: D,
  AddAuditReportActionSchema: T,
  AddAuditReportInputSchema: z2,
  AddCommentActionSchema: C,
  AddCommentInputSchema: L,
  AddLineItemActionSchema: O,
  AddLineItemInputSchema: U,
  AddVestingActionSchema: N,
  AddVestingInputSchema: R,
  Add_AccountSchema: d,
  Add_Audit_ReportSchema: b,
  Add_CommentSchema: f,
  Add_Line_ItemSchema: _,
  Add_VestingSchema: A,
  AuditReportSchema: n,
  AuditReportStatusSchema: v,
  BudgetStatementActionSchema: Wt,
  BudgetStatementDataInputSchema: F,
  BudgetStatementDataSchema: M,
  BudgetStatementInputSchema: Ht,
  BudgetStatementSchema: qt,
  BudgetStatusSchema: r,
  CommentAuthorInputSchema: o,
  CommentAuthorSchema: V,
  CommentInputSchema: P,
  CommentSchema: a,
  CommentUpdateInputSchema: w,
  DeleteAccountActionSchema: q,
  DeleteAccountInputSchema: W,
  DeleteAuditReportActionSchema: H,
  DeleteAuditReportInputSchema: Y,
  DeleteCommentActionSchema: J,
  DeleteCommentInputSchema: K,
  DeleteLineItemActionSchema: X,
  DeleteLineItemInputSchema: Z,
  DeleteVestingActionSchema: $,
  DeleteVestingInputSchema: tt,
  Delete_AccountSchema: x,
  Delete_Audit_ReportSchema: B,
  Delete_CommentSchema: k,
  Delete_Line_ItemSchema: G,
  Delete_VestingSchema: Q,
  DocumentFileInputSchema: et,
  FtesForecastInputSchema: rt,
  FtesForecastSchema: nt,
  FtesInputSchema: ut,
  FtesSchema: c,
  LineItemCategorySchema: m,
  LineItemDeleteInputSchema: at,
  LineItemForecastSchema: u,
  LineItemGroupSchema: s,
  LineItemInputSchema: h,
  LineItemSchema: l,
  LineItemUpdateInputSchema: ot,
  LineItemsSortInputSchema: ct,
  LoadStateActionInputSchema: lt,
  LoadStateActionSchema: Yt,
  LoadStateActionStateInputSchema: mt,
  Load_StateSchema: it,
  OperationSchema: Jt,
  OwnerInputSchema: st,
  OwnerSchema: p,
  PruneActionInputSchema: pt,
  PruneActionSchema: Kt,
  PruneSchema: ht,
  RedoActionSchema: Xt,
  RedoSchema: St,
  SetFtesActionSchema: jt,
  SetMonthActionSchema: It,
  SetNameActionSchema: Zt,
  SetNameOperationSchema: $t,
  SetOwnerActionSchema: Et,
  SetQuoteCurrencyActionSchema: Dt,
  Set_FtesSchema: gt,
  Set_MonthSchema: yt,
  Set_NameSchema: dt,
  Set_OwnerSchema: bt,
  Set_Quote_CurrencySchema: ft,
  SortAccountsActionSchema: Tt,
  SortAccountsInputSchema: zt,
  SortLineItemsActionSchema: Ct,
  SortLineItemsInputSchema: Lt,
  Sort_AccountsSchema: _t,
  Sort_Line_ItemsSchema: At,
  UndoActionSchema: te,
  UndoSchema: Ot,
  UpdateAccountActionSchema: Mt,
  UpdateAccountInputSchema: Ft,
  UpdateCommentActionSchema: Vt,
  UpdateCommentInputSchema: Pt,
  UpdateLineItemActionSchema: wt,
  UpdateLineItemInputSchema: xt,
  UpdateVestingActionSchema: Bt,
  UpdateVestingInputSchema: kt,
  Update_AccountSchema: Ut,
  Update_CommentSchema: Nt,
  Update_Line_ItemSchema: Rt,
  Update_VestingSchema: vt,
  VestingInputSchema: Gt,
  VestingSchema: S,
  VestingUpdateInputSchema: Qt,
  definedNonNullAnySchema: y,
  isDefinedNonNullAny: g
}, Symbol.toStringTag, { value: "Module" }));
Object.freeze(Object.defineProperty({
  __proto__: null,
  z: ee
}, Symbol.toStringTag, { value: "Module" }));

const ADD_ACCOUNT = "ADD_ACCOUNT";
const UPDATE_ACCOUNT = "UPDATE_ACCOUNT";
const DELETE_ACCOUNT = "DELETE_ACCOUNT";
const SORT_ACCOUNTS = "SORT_ACCOUNTS";

const ADD_AUDIT_REPORT = "ADD_AUDIT_REPORT";
const DELETE_AUDIT_REPORT = "DELETE_AUDIT_REPORT";

const SET_OWNER = "SET_OWNER";
const SET_MONTH = "SET_MONTH";
const SET_QUOTE_CURRENCY = "SET_QUOTE_CURRENCY";
const SET_FTES = "SET_FTES";

const ADD_COMMENT = "ADD_COMMENT";
const UPDATE_COMMENT = "UPDATE_COMMENT";
const DELETE_COMMENT = "DELETE_COMMENT";

const ADD_LINE_ITEM = "ADD_LINE_ITEM";
const UPDATE_LINE_ITEM = "UPDATE_LINE_ITEM";
const DELETE_LINE_ITEM = "DELETE_LINE_ITEM";
const SORT_LINE_ITEMS = "SORT_LINE_ITEMS";

const ADD_VESTING = "ADD_VESTING";
const UPDATE_VESTING = "UPDATE_VESTING";
const DELETE_VESTING = "DELETE_VESTING";

function createBudgetStatement(initialState) {
  return createDocument({
    documentType: "powerhouse/budget-statement",
    ...initialState,
    state: {
      owner: {
        ref: null,
        id: null,
        title: null
      },
      month: null,
      quoteCurrency: null,
      vesting: [],
      ftes: null,
      accounts: [],
      auditReports: [],
      comments: [],
      ...initialState?.state
    }
  });
}
const createAccount = (input) => ({
  ...input,
  name: input.name ?? "",
  lineItems: input.lineItems?.map(createLineItem) ?? new Array()
});
const createLineItem = (input) => ({
  budgetCap: null,
  payment: null,
  actual: null,
  comment: null,
  ...input,
  forecast: input.forecast?.sort((f1, f2) => f1.month.localeCompare(f2.month)) ?? new Array(),
  headcountExpense: input.headcountExpense ?? false,
  group: input.group ?? null,
  category: input.category ?? null
});
const saveBudgetStatementToFile = (document, path, name) => {
  return saveToFile(document, path, "phbs", name);
};
const loadBudgetStatementFromFile = async (path) => {
  const document = await loadFromFile(path, reducer);
  return {
    ...document
    // fileRegistry
  };
};
const loadBudgetStatementFromInput = async (input) => {
  const document = await loadFromInput(input, reducer);
  return {
    ...document
    // fileRegistry
  };
};
const saveBudgetStatementToFileHandle = async (document, input) => {
  return saveToFileHandle(document, input);
};

var utils = /*#__PURE__*/Object.freeze({
  __proto__: null,
  createAccount: createAccount,
  createBudgetStatement: createBudgetStatement,
  createLineItem: createLineItem,
  loadBudgetStatementFromFile: loadBudgetStatementFromFile,
  loadBudgetStatementFromInput: loadBudgetStatementFromInput,
  saveBudgetStatementToFile: saveBudgetStatementToFile,
  saveBudgetStatementToFileHandle: saveBudgetStatementToFileHandle
});

const addAccountOperation = (state, action) => {
  action.input.accounts.forEach((input) => {
    if (state.accounts.find((account) => account.address === input.address)) {
      throw new Error(
        `Account with address ${input.address} already exists!`
      );
    }
    state.accounts.push(createAccount(input));
  });
};
const updateAccountOperation = (state, action) => {
  state.accounts = state.accounts.map((account) => {
    const accountUpdate = action.input.accounts.find(
      (a) => a.address === account.address
    );
    return {
      ...account,
      lineItems: accountUpdate?.lineItems ?? account.lineItems,
      name: accountUpdate?.name ?? account.name
    };
  });
};
const deleteAccountOperation = (state, action) => {
  state.accounts = state.accounts.filter(
    (account) => !action.input.accounts.find((address) => address === account.address)
  );
};
const sortAccountsOperation = (state, action) => {
  state.accounts.sort((a, b) => {
    const index1 = action.input.accounts.indexOf(a.address);
    const index2 = action.input.accounts.indexOf(b.address);
    return (index1 > -1 ? index1 : Infinity) - (index2 > -1 ? index2 : Infinity);
  });
};

function checkDuplicatedReport(state, report) {
  if (state.auditReports.find((audit) => audit.report === report)) {
    throw new Error(`Audit with report ${report} already exists`);
  }
}
const addAuditReportOperation = (state, action) => {
  action.input.reports.forEach((audit) => {
    checkDuplicatedReport(state, audit.report);
    state.auditReports.push(audit);
  });
};
const deleteAuditReportOperation = (state, action) => {
  action.input.reports.forEach((report) => {
    const index = state.auditReports.findIndex(
      (audit) => audit.report === report
    );
    if (index > -1) {
      state.auditReports.splice(index, 1);
    }
  });
};

const setOwnerOperation = (state, action) => {
  state.owner = {
    id: action.input.id ?? null,
    ref: action.input.ref ?? null,
    title: action.input.title ?? null
  };
};
const setMonthOperation = (state, action) => {
  state.month = action.input;
};
const setQuoteCurrencyOperation = (state, action) => {
  state.quoteCurrency = action.input;
};
const setFtesOperation = (state, action) => {
  state.ftes = action.input;
  state.ftes?.forecast.sort((f1, f2) => f1.month.localeCompare(f2.month));
};

function isEqual(lineItemInput, lineItem) {
  return lineItemInput.category === lineItem.category?.id && lineItemInput.group === lineItem.group?.id;
}
const addLineItemOperation = (state, action) => {
  const account = state.accounts.find(
    (a) => a.address === action.input.account
  );
  if (!account) {
    throw new Error(
      `Account with address ${action.input.account} not found`
    );
  }
  action.input.lineItems.forEach((input) => {
    if (account.lineItems.find(
      (item) => input.category?.id === item.category?.id && input.group?.id === item.group?.id
    )) {
      throw new Error(
        `Line item with category '${input.category?.id ?? "null"}' and group '${input.group?.id ?? "null"}' already exists`
      );
    }
    account.lineItems.push(createLineItem(input));
  });
};
const updateLineItemOperation = (state, action) => {
  const account = state.accounts.find(
    (a) => a.address === action.input.account
  );
  if (!account) {
    throw new Error(
      `Account with address ${action.input.account} not found`
    );
  }
  account.lineItems = account.lineItems.map((lineItem) => {
    const input = action.input.lineItems.find((l) => isEqual(l, lineItem));
    if (!input) {
      return lineItem;
    } else {
      return {
        ...lineItem,
        ...input,
        category: lineItem.category,
        headcountExpense: input.headcountExpense ?? false,
        group: lineItem.group,
        forecast: (input.forecast ?? lineItem.forecast).sort((f1, f2) => f1.month.localeCompare(f2.month))
      };
    }
  });
};
const deleteLineItemOperation = (state, action) => {
  const account = state.accounts.find(
    (a) => a.address === action.input.account
  );
  if (!account) {
    throw new Error(
      `Account with address ${action.input.account} not found`
    );
  }
  account.lineItems = account.lineItems.filter(
    (lineItem) => !action.input.lineItems.find((l) => isEqual(l, lineItem))
  );
};
const sortLineItemsOperation = (state, action) => {
  const account = state.accounts.find(
    (a) => a.address === action.input.account
  );
  if (!account) {
    throw new Error(
      `Account with address ${action.input.account} not found`
    );
  }
  account.lineItems.sort((a, b) => {
    const index1 = action.input.lineItems.findIndex((l) => isEqual(l, a));
    const index2 = action.input.lineItems.findIndex((l) => isEqual(l, b));
    return (index1 > -1 ? index1 : Infinity) - (index2 > -1 ? index2 : Infinity);
  });
};

const sortComment = (a, b) => a.timestamp < b.timestamp ? -1 : 1;
const addCommentOperation = (state, action) => {
  action.input.comments.forEach((input) => {
    const key = input.key ?? hashKey();
    const index = state.comments.findIndex((c) => c.key === input.key);
    if (index > -1) {
      throw new Error(`Comment with key ${key} already exists`);
    }
    state.comments.push({
      key,
      author: {
        ref: null,
        id: null,
        username: null,
        roleLabel: null,
        ...input.author
      },
      comment: input.comment,
      timestamp: input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
      status: input.status ?? "Draft"
    });
  });
  state.comments.sort(sortComment);
};
const updateCommentOperation = (state, action) => {
  action.input.comments.forEach((input) => {
    const index = state.comments.findIndex((c) => c.key === input.key);
    if (index === -1) {
      return;
    }
    const comment = state.comments[index];
    state.comments[index] = {
      ...comment,
      ...input,
      author: {
        id: input.author?.id ?? comment.author.id,
        ref: input.author?.ref ?? comment.author.ref,
        roleLabel: input.author?.roleLabel ?? comment.author.roleLabel,
        username: input.author?.username ?? comment.author.username
      },
      comment: input.comment ?? comment.comment,
      timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
      status: input.status ?? comment.status
    };
  });
  state.comments.sort(sortComment);
};
const deleteCommentOperation = (state, action) => {
  state.comments = state.comments.filter(
    (comment) => !action.input.comments.includes(comment.key)
  );
};

const sortVesting = (a, b) => a.date < b.date ? -1 : 1;
const addVestingOperation = (state, action) => {
  action.input.vesting.forEach((input) => {
    const key = input.key ?? hashKey();
    const index = state.vesting.findIndex((v) => v.key === input.key);
    if (index > -1) {
      throw new Error(`Vesting with key ${key} already exists`);
    }
    state.vesting.push({
      ...input,
      key,
      date: input.date ?? "",
      amount: input.amount ?? "",
      amountOld: input.amountOld ?? input.amount ?? "",
      comment: input.comment ?? "",
      currency: input.currency ?? "",
      vested: input.vested ?? false
    });
  });
  state.vesting.sort(sortVesting);
};
const updateVestingOperation = (state, action) => {
  action.input.vesting.forEach((input) => {
    const index = state.vesting.findIndex((v) => v.key === input.key);
    if (index === -1) {
      return;
    }
    const vesting = state.vesting[index];
    state.vesting[index] = {
      ...vesting,
      ...input,
      amount: input.amount ?? vesting.amount,
      amountOld: input.amountOld ?? vesting.amountOld,
      comment: input.comment ?? vesting.comment,
      currency: input.currency ?? vesting.currency,
      date: input.date ?? vesting.date,
      vested: input.vested ?? vesting.vested
    };
  });
  state.vesting.sort(sortVesting);
};
const deleteVestingOperation = (state, action) => {
  state.vesting = state.vesting.filter(
    (vesting) => !action.input.vesting.includes(vesting.key)
  );
};

const reducer = createReducer((state, action) => {
  if (isBaseAction(action)) {
    return state;
  }
  ee.BudgetStatementActionSchema().parse(action);
  switch (action.type) {
    case SET_OWNER:
      return setOwnerOperation(state, action);
    case SET_MONTH:
      return setMonthOperation(state, action);
    case SET_QUOTE_CURRENCY:
      return setQuoteCurrencyOperation(state, action);
    case SET_FTES:
      return setFtesOperation(state, action);
    case ADD_ACCOUNT:
      return addAccountOperation(state, action);
    case UPDATE_ACCOUNT:
      return updateAccountOperation(state, action);
    case DELETE_ACCOUNT:
      return deleteAccountOperation(state, action);
    case SORT_ACCOUNTS:
      return sortAccountsOperation(state, action);
    case ADD_LINE_ITEM:
      return addLineItemOperation(state, action);
    case UPDATE_LINE_ITEM:
      return updateLineItemOperation(state, action);
    case DELETE_LINE_ITEM:
      return deleteLineItemOperation(state, action);
    case SORT_LINE_ITEMS:
      return sortLineItemsOperation(state, action);
    case ADD_AUDIT_REPORT:
      return addAuditReportOperation(state, action);
    case DELETE_AUDIT_REPORT:
      return deleteAuditReportOperation(state, action);
    case ADD_VESTING:
      return addVestingOperation(state, action);
    case UPDATE_VESTING:
      return updateVestingOperation(state, action);
    case DELETE_VESTING:
      return deleteVestingOperation(state, action);
    case ADD_COMMENT:
      return addCommentOperation(state, action);
    case UPDATE_COMMENT:
      return updateCommentOperation(state, action);
    case DELETE_COMMENT:
      return deleteCommentOperation(state, action);
    default:
      return state;
  }
});

const addAccount = (accounts) => createAction(
  ADD_ACCOUNT,
  {
    accounts: accounts.map(createAccount)
  },
  void 0,
  ee.AddAccountActionSchema
);
const updateAccount = (accounts) => createAction(
  UPDATE_ACCOUNT,
  { accounts },
  void 0,
  ee.UpdateAccountActionSchema
);
const deleteAccount = (accounts) => createAction(
  DELETE_ACCOUNT,
  { accounts },
  void 0,
  ee.DeleteAccountActionSchema
);
const sortAccounts = (accounts) => createAction(
  SORT_ACCOUNTS,
  { accounts },
  void 0,
  ee.SortAccountsActionSchema
);

const addAuditReport = (reports, attachments) => {
  return createAction(
    ADD_AUDIT_REPORT,
    { reports },
    attachments,
    ee.AddAuditReportActionSchema
  );
};
const deleteAuditReport = (reports) => createAction(
  DELETE_AUDIT_REPORT,
  { reports },
  void 0,
  ee.DeleteAuditReportActionSchema
);

const setOwner = (owner) => createAction(
  SET_OWNER,
  owner,
  void 0,
  ee.SetOwnerActionSchema
);
const setMonth = (month) => createAction(
  SET_MONTH,
  month,
  void 0,
  ee.SetMonthActionSchema
);
const setQuoteCurrency = (currency) => createAction(
  SET_QUOTE_CURRENCY,
  currency,
  void 0,
  ee.SetQuoteCurrencyActionSchema
);
const setFtes = (ftes) => createAction(
  SET_FTES,
  ftes,
  void 0,
  ee.SetFtesActionSchema
);

const addComment = (comments) => createAction(
  ADD_COMMENT,
  { comments },
  void 0,
  ee.AddCommentActionSchema
);
const updateComment = (comments) => createAction(
  UPDATE_COMMENT,
  { comments },
  void 0,
  ee.UpdateCommentActionSchema
);
const deleteComment = (comments) => createAction(
  DELETE_COMMENT,
  { comments },
  void 0,
  ee.DeleteCommentActionSchema
);

const addLineItem = (account, lineItems) => createAction(
  ADD_LINE_ITEM,
  {
    account,
    lineItems: lineItems.map(createLineItem)
  },
  void 0,
  ee.AddLineItemActionSchema
);
const updateLineItem = (account, lineItems) => createAction(
  UPDATE_LINE_ITEM,
  {
    account,
    lineItems
  },
  void 0,
  ee.UpdateLineItemActionSchema
);
const deleteLineItem = (account, lineItems) => createAction(
  DELETE_LINE_ITEM,
  {
    account,
    lineItems
  },
  void 0,
  ee.DeleteLineItemActionSchema
);
const sortLineItems = (account, lineItems) => createAction(
  SORT_LINE_ITEMS,
  {
    account,
    lineItems
  },
  void 0,
  ee.SortLineItemsActionSchema
);

const addVesting = (vesting) => createAction(
  ADD_VESTING,
  { vesting },
  void 0,
  ee.AddVestingActionSchema
);
const updateVesting = (vesting) => createAction(
  UPDATE_VESTING,
  { vesting },
  void 0,
  ee.UpdateVestingActionSchema
);
const deleteVesting = (vesting) => createAction(
  DELETE_VESTING,
  { vesting },
  void 0,
  ee.DeleteVestingActionSchema
);

class AccountObject extends BaseDocument {
  /**
   * Adds one or more accounts to the budget statement.
   * @param accounts An array of AccountInput objects to add.
   *
   * @group Account
   */
  addAccount(accounts) {
    const action = addAccount(accounts);
    return this.dispatch(action);
  }
  /**
   * Updates one or more existing accounts in the budget statement.
   * @param accounts An array of AccountInput objects to update.
   *
   * @group Account
   */
  updateAccount(accounts) {
    return this.dispatch(updateAccount(accounts));
  }
  /**
   * Deletes one or more accounts from the budget statement.
   * @param accounts An array of addresses of the accounts to delete.
   *
   * @group Account
   */
  deleteAccount(accounts) {
    return this.dispatch(deleteAccount(accounts));
  }
  /**
   * Sorts the accounts inthe budget statement.
   * @param accounts An array of addresses of the accounts to sort.
   *
   * @group Account
   */
  sortAccounts(accounts) {
    return this.dispatch(sortAccounts(accounts));
  }
  /**
   * Returns an array of all accounts in the budget statement.
   *
   * @group Account
   */
  get accounts() {
    return this.state.accounts;
  }
  /**
   * Returns the Account object with the specified address.
   * @param address The address of the Account to retrieve.
   *
   * @group Account
   */
  getAccount(address) {
    return this.accounts.find((account) => account.address === address);
  }
}

class AuditObject extends BaseDocument {
  /**
   * Adds audit reports to the budget statement.
   * @param reports - An array of audit report objects to add.
   *
   * @group Audit
   */
  addAuditReport(reports, attachments) {
    return this.dispatch(addAuditReport(reports, attachments));
  }
  /**
   * Deletes audit reports from the budget statement.
   * @param reports - An array of objects that contain the report attachment name of the audits items to be deleted.
   *
   * @group Audit
   */
  deleteAuditReport(reports) {
    return this.dispatch(deleteAuditReport(reports));
  }
  /**
   * Retrieves all audit reports from the budget statement.
   * @returns An array of audit report objects.
   *
   * @group Audit
   */
  getAuditReports() {
    return this.state.auditReports;
  }
  /**
   * Retrieves a specific audit report from the budget statement.
   * @param report - The name of the attachment of the report to be retrieved.
   * @returns The audit report object if it exists, or undefined if not.
   *
   * @group Audit
   */
  getAuditReport(report) {
    return this.getAuditReports().find((audit) => audit.report === report);
  }
}

class BaseObject extends BaseDocument {
  /**
   * Gets the month of the budget statement.
   * @category Budget Statement
   */
  get month() {
    return this.state.month;
  }
  /**
   * Gets the owner of the budget statement.
   * @category Budget Statement
   */
  get owner() {
    return this.state.owner;
  }
  /**
   * Gets the quote currency of the budget statement.
   * @category Budget Statement
   */
  get quoteCurrency() {
    return this.state.quoteCurrency;
  }
  get ftes() {
    return this.state.ftes;
  }
  setOwner(owner) {
    return this.dispatch(setOwner(owner));
  }
  setMonth(month) {
    return this.dispatch(setMonth(month));
  }
  setQuoteCurrency(currency) {
    return this.dispatch(setQuoteCurrency(currency));
  }
  setFtes(ftes) {
    return this.dispatch(setFtes(ftes));
  }
}

class CommentObject extends BaseDocument {
  addComment(comments) {
    return this.dispatch(addComment(comments));
  }
  updateComment(comments) {
    return this.dispatch(updateComment(comments));
  }
  deleteComment(comments) {
    return this.dispatch(deleteComment(comments));
  }
  get comments() {
    return this.state.comments;
  }
  getComment(key) {
    return this.state.comments.find((v) => v.key === key);
  }
}

class LineItemObject extends BaseDocument {
  /**
   * Adds a line item to the specified account.
   * @param account The address of the account to which the line item will be added.
   * @param lineItems An array of line item objects to be added to the account.
   *
   * @group Line Item
   */
  addLineItem(account, lineItems) {
    return this.dispatch(addLineItem(account, lineItems));
  }
  /**
   * Updates line items for the specified account.
   * @param account The address of the account for which line items will be updated.
   * @param lineItems An array of line item input objects to be updated.
   *
   * @group Line Item
   */
  updateLineItem(account, lineItems) {
    return this.dispatch(updateLineItem(account, lineItems));
  }
  /**
   * Deletes line items for the specified account.
   * @param account The address of the account for which line items will be deleted.
   * @param lineItems An array of objects that contain the category and group of the line items to be deleted.
   *
   * @group Line Item
   */
  deleteLineItem(account, lineItems) {
    return this.dispatch(deleteLineItem(account, lineItems));
  }
  /**
   * Sorts the line items of an account.
   *
   * @param account - The account containing the line items to sort.
   * @param lineItems - An array of line items to sort.
   * @group Line Item
   */
  sortLineItems(account, lineItems) {
    return this.dispatch(sortLineItems(account, lineItems));
  }
  /**
   * Retrieves line items for the specified account.
   * @param account The address of the account for which line items will be retrieved.
   * @returns An array of line item objects for the specified account, or undefined if the account does not exist.
   *
   * @group Line Item
   */
  getLineItems(account) {
    return this.state.accounts.find(({ address }) => address === account)?.lineItems;
  }
  /**
   * Retrieves a specific line item for the specified account.
   * @param account The address of the account for which the line item will be retrieved.
   * @param lineItem An object that contains the category and group of the line item to be retrieved.
   * @returns The line item object that matches the specified category and group, or undefined if it does not exist.
   *
   * @group Line Item
   */
  getLineItem(account, lineItem) {
    return this.getLineItems(account)?.find(
      ({ category, group }) => category?.id === lineItem.category && group?.id === lineItem.group
    );
  }
}

class VestingObject extends BaseDocument {
  addVesting(vesting) {
    return this.dispatch(addVesting(vesting));
  }
  updateVesting(vesting) {
    return this.dispatch(updateVesting(vesting));
  }
  deleteVesting(vesting) {
    return this.dispatch(deleteVesting(vesting));
  }
  get vesting() {
    return this.state.vesting;
  }
  getVesting(key) {
    return this.state.vesting.find((v) => v.key === key);
  }
}

let BudgetStatement$2 = class BudgetStatement extends BaseDocument {
  /**
   * The file extension used to save budget statements.
   */
  static fileExtension = "phbs";
  /**
   *
   * Creates a new BudgetStatement instance.
   * @param initialState - An optional object representing the initial state of the BudgetStatement.
   */
  constructor(initialState) {
    const document = createBudgetStatement(initialState);
    super(reducer, document);
  }
  /**
   * Saves the budget statement to a file.
   *
   * @param path The path to the file to save.
   * @returns A promise that resolves when the save operation completes.
   */
  saveToFile(path, name) {
    return super.saveToFile(path, BudgetStatement.fileExtension, name);
  }
  /**
   * Loads the budget statement from a file.
   *
   * @param path The path to the file to load.
   * @returns A promise that resolves with the loaded `BudgetStatement` instance.
   */
  loadFromFile(path) {
    return super.loadFromFile(path);
  }
  /**
   * Creates a new `BudgetStatement` instance from a file.
   *
   * @param path The path to the file to load.
   * @returns A promise that resolves with the loaded `BudgetStatement` instance.
   */
  static async fromFile(path) {
    const budgetStatement = new this();
    await budgetStatement.loadFromFile(path);
    return budgetStatement;
  }
};
applyMixins(BudgetStatement$2, [
  AccountObject,
  AuditObject,
  CommentObject,
  BaseObject,
  LineItemObject,
  VestingObject
]);

var gen = /*#__PURE__*/Object.freeze({
  __proto__: null,
  BudgetStatement: BudgetStatement$2,
  addAccount: addAccount,
  addAuditReport: addAuditReport,
  addComment: addComment,
  addLineItem: addLineItem,
  addVesting: addVesting,
  deleteAccount: deleteAccount,
  deleteAuditReport: deleteAuditReport,
  deleteComment: deleteComment,
  deleteLineItem: deleteLineItem,
  deleteVesting: deleteVesting,
  setFtes: setFtes,
  setMonth: setMonth,
  setOwner: setOwner,
  setQuoteCurrency: setQuoteCurrency,
  sortAccounts: sortAccounts,
  sortLineItems: sortLineItems,
  updateAccount: updateAccount,
  updateComment: updateComment,
  updateLineItem: updateLineItem,
  updateVesting: updateVesting
});

const { BudgetStatement, ...BudgetActions } = gen;
const actions = { ...BaseActions, ...BudgetActions };
var index = {
  actions,
  reducer,
  utils,
  BudgetStatement
};

var BudgetStatement$1 = /*#__PURE__*/Object.freeze({
  __proto__: null,
  BudgetStatement: BudgetStatement,
  actions: actions,
  default: index,
  reducer: reducer,
  utils: utils
});

export { BudgetStatement$1 as B, BudgetStatement as a, actions as b, index as i, reducer as r, utils as u };
//# sourceMappingURL=index-8f3fd972.js.map
