import { r as registerInstance, c as createEvent, h, g as getElement } from './index-08b73e9e.js';
import { E as Error, i as invalidContent, b as backendFailure } from './unknown-97022c22.js';
import './App-364e27cc.js';
import { I as Identifier } from './Token-ba2c5d5c.js';
import { N as Notice } from './Notice-668f9bc7.js';
import { C as Contact } from './Item-f4cbd6f4.js';
import { c as Customer, I as Item, d as Schedule } from './index-3299c1c0.js';
import './Credentials-b84c0c5f.js';
import { d as dist } from './index-a0a71287.js';
import { P as PayfuncPortal } from './index-84a8301a.js';
import { d as dist$1 } from './index-8ba22472.js';
import { d as dist$2 } from './index-3cf720d3.js';
import './_commonjsHelpers-9943807e.js';
import './index-1f953d81.js';
import './TextDecoder-357ac2ce.js';
import './index-26d778c4.js';

const sv$7 = {
  "Create order": "Skapa order",
  Cancel: "Avbryt",
  "Retrying payment.": "Försöker betalning igen.",
  "Your payment was declined.": "Betalningen nekades.",
  "Payment succeeded.": "Betalning genomförd.",
  "Retry payment": "Försök betala",
  "Create subscription": "Skapa prenumeration",
  "Equalize balance to zero": "Justera saldot till noll",
  "Equalizing balance...": "Justerar saldo...",
  "$0 of $1 balances were equalized.": "$0 av $1 saldon har justerats.",
  "Balance was equalized.": "Saldot har justerats.",
  "Failed to equalize $0 of $1 balances.": "Kunde inte justera $0 av $1 saldon.",
  "Failed to equalize balance.": "Kunde inte justera saldo.",
};

function create$7(language) {
  return dist.create({
    sv: sv$7,
  }, language);
}

const styleCss$7 = ".sc-ig-customer-actions-h{display:-ms-flexbox;display:flex;-ms-flex-flow:column;flex-flow:column}[hidden].sc-ig-customer-actions-h{display:none}div.sc-ig-customer-actions:first-of-type{z-index:3;padding:0.5em 0 0.5em 0.4em;overflow:hidden;position:fixed;top:8.5em;right:-3.3em;background-color:rgb(var(--smoothly-medium-tint));border-radius:0.3em 0 0 0.3em;-webkit-box-shadow:var(--smoothly-shadow);box-shadow:var(--smoothly-shadow);-webkit-transition:right ease-in-out 0.3s;transition:right ease-in-out 0.3s}.sc-ig-customer-actions-h>div.sc-ig-customer-actions>smoothly-trigger.sc-ig-customer-actions{border-radius:0;border:solid 1px rgb(var(--smoothly-color))}@-webkit-keyframes slide{0%{width:0}}@keyframes slide{0%{width:0}}.sc-ig-customer-actions-h>portal-create-order.sc-ig-customer-actions,.sc-ig-customer-actions-h>ig-subscription-create.sc-ig-customer-actions{background-color:rgb(var(--smoothly-medium-contrast));border:solid 1px rgb(var(--smoothly-medium-shade));-webkit-box-shadow:var(--smoothly-shadow);box-shadow:var(--smoothly-shadow);border-radius:0.6em;position:fixed;z-index:3;right:5em;padding:1em}.sc-ig-customer-actions-h>portal-create-order.sc-ig-customer-actions{padding-bottom:0.5em;top:6em}.sc-ig-customer-actions-h>ig-subscription-create.sc-ig-customer-actions{top:9em}.arrow.sc-ig-customer-actions{background-color:rgb(var(--smoothly-medium-contrast));border-color:rgb(var(--smoothly-medium-shade));width:30px;height:30px;border-top-style:solid;border-top-width:1px;border-right-style:solid;border-right-width:1px;position:fixed;z-index:3;right:4em;-webkit-transform:rotate(45deg);transform:rotate(45deg)}.sc-ig-customer-actions-h>portal-create-order.sc-ig-customer-actions+.arrow.sc-ig-customer-actions{top:9.5em}.sc-ig-customer-actions-h>ig-subscription-create.sc-ig-customer-actions+.arrow.sc-ig-customer-actions{top:12em}.sc-ig-customer-actions-h .background.sc-ig-customer-actions{position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2;background:rgba(var(--smoothly-warning-contrast), 0.5)}";

const IntergiroCustomerActions = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.selected = {};
  }
  componentWillLoad() {
    this.t = create$7(this.element);
  }
  retry() {
    this.notice.emit(Notice.execute(this.t("Retrying payment."), async () => {
      var _a;
      const response = await ((_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.customer.retryPayment());
      return Error.is(response)
        ? [false, this.t("Your payment was declined.")]
        : [true, this.t("Payment succeeded.")];
    }));
  }
  equalize() {
    const idArray = Object.keys(this.selected);
    this.notice.emit(Notice.execute(this.t("Equalizing balance..."), async () => {
      let result;
      const response = await Promise.all(idArray.map(id => { var _a; return (_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.customer.equalizeBalance(id); }));
      const [succeeded, failed] = response.reduce(([s, f], e) => (Error.is(e) ? [s, ++f] : [++s, f]), [0, 0]);
      if (succeeded > 0)
        result = [
          true,
          idArray.length > 1
            ? this.t("$0 of $1 balances were equalized.", succeeded, idArray.length)
            : this.t("Balance was equalized."),
        ];
      else
        result = [
          false,
          idArray.length > 1
            ? this.t("Failed to equalize $0 of $1 balances.", failed, idArray.length)
            : this.t("Failed to equalize balance."),
        ];
      return result;
    }));
  }
  toggle(action) {
    this.opened = action == this.opened ? "" : action;
  }
  render() {
    const customers = Object.values(this.selected).filter(Customer.is);
    const retry = customers.every(c => c.status == "suspended" || c.status == "pending");
    return [
      h("div", { style: customers.length > 0 ? { right: "0" } : {} }, h("smoothly-trigger", { color: "success", name: "cancel", onClick: () => this.toggle("order") }, h("smoothly-icon", { toolTip: this.opened == "order" ? this.t("Cancel") : this.t("Create order"), name: this.opened == "order" ? "close" : "add" })), h("smoothly-trigger", { hidden: !this.whitelist, slot: "icon", color: "success", onClick: () => this.toggle("subscription") }, h("smoothly-icon", { toolTip: this.t("Create subscription"), name: "calendar-outline" })), h("smoothly-trigger", { color: "warning", hidden: !this.whitelist, slot: "icon", onClick: () => this.equalize() }, h("smoothly-icon", { toolTip: this.t("Equalize balance to zero"), name: "cash-outline" })), h("smoothly-trigger", { color: "danger", disabled: !retry, name: "retry", onClick: () => this.retry() }, h("smoothly-icon", { toolTip: this.t("Retry payment"), name: "refresh" }))),
      (this.opened == "order" || this.opened == "subscription") && Object.entries(this.selected).length > 0
        ? [
          this.opened == "order" ? (h("portal-create-order", { type: "customer", selected: this.selected })) : (h("ig-subscription-create", { client: PayfuncPortal.client, customers: this.selected })),
          h("div", { class: "arrow" }),
          h("div", { class: "background", onClick: () => this.toggle(this.opened) }),
        ]
        : "",
    ];
  }
  get element() { return getElement(this); }
};
IntergiroCustomerActions.style = styleCss$7;

const sv$6 = {
  "Customer number": "Kundnummer",
  Name: "Namn",
  Email: "E-post",
  "Create customer": "Skapa kund",
  "Failed to create customer.": "Kunde inte skapa kund.",
  "Customer was created.": "Kunden skapades.",
  "Creating customer...": "Skapar kund...",
};

function create$6(language) {
  return dist.create({
    sv: sv$6,
  }, language);
}

const styleCss$6 = ".sc-ig-customer-create-h>form.sc-ig-customer-create{width:100%;-ms-flex-wrap:wrap;flex-wrap:wrap;display:-ms-flexbox;display:flex}section.sc-ig-customer-create{display:-ms-flexbox;display:flex;-ms-flex-positive:1;flex-grow:1}section.sc-ig-customer-create:last-of-type{-ms-flex-positive:2;flex-grow:2;min-width:calc(100% - 45px)}section.sc-ig-customer-create>smoothly-input.sc-ig-customer-create{border:1px solid rgb(var(--smoothly-medium-color));margin-bottom:0.5em;margin-left:-1px;-ms-flex-positive:1;flex-grow:1}section.sc-ig-customer-create:last-of-type>smoothly-submit.sc-ig-customer-create{float:right;margin-bottom:0.5em;border:none}section.sc-ig-customer-create:first-of-type{-ms-flex-wrap:wrap;flex-wrap:wrap}section.sc-ig-customer-create:first-of-type>*.sc-ig-customer-create:first-of-type{-ms-flex-positive:1;flex-grow:1;-ms-flex-preferred-size:8em;flex-basis:8em}section.sc-ig-customer-create:first-of-type>*.sc-ig-customer-create:last-of-type{-ms-flex-positive:3;flex-grow:3}smoothly-icon.sc-ig-customer-create{cursor:pointer;float:right}";

const IntergiroCustomerCreate = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.createCustomer = createEvent(this, "createCustomer", 7);
    this.notice = createEvent(this, "notice", 7);
    this.close = createEvent(this, "close", 7);
  }
  componentWillLoad() {
    this.customerNumber = Identifier.generate(12);
    this.t = create$6(this.element);
  }
  async submitCustomer(event) {
    const customer = {
      number: event.detail.number,
      contact: {
        name: event.detail.name == "" ? undefined : event.detail.name,
        email: event.detail.email == "" ? undefined : event.detail.email,
      },
      method: [],
    };
    this.notice.emit(Notice.execute(this.t("Creating customer..."), async () => {
      var _a, _b;
      let result;
      this.close.emit();
      const response = await ((_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.customer.create(customer));
      if (!Error.is(response)) {
        result = [true, this.t("Customer was created.")];
        const customers = await ((_b = PayfuncPortal.client) === null || _b === void 0 ? void 0 : _b.customer.list());
        this.createCustomer.emit(customers);
      }
      else
        result = [false, this.t("Failed to create customer.")];
      return result;
    }));
  }
  render() {
    return [
      h("form", null, h("section", null, h("smoothly-input", { name: "number", type: "text", value: this.customerNumber }, this.t("Customer number")), h("smoothly-input", { name: "name", type: "text" }, this.t("Name"))), h("section", null, h("smoothly-input", { name: "email", type: "text" }, this.t("Email")), h("smoothly-submit", { fill: "clear", prevent: true, onSubmit: (e) => this.submitCustomer(e) }, h("smoothly-icon", { toolTip: this.t("Create customer"), name: "add-circle", fill: "clear", size: "medium", color: "success" })))),
    ];
  }
  get element() { return getElement(this); }
};
IntergiroCustomerCreate.style = styleCss$6;

const sv$5 = {
  "Create customer": "Skapa kund",
  Close: "Stäng",
};

function create$5(language) {
  return dist.create({
    sv: sv$5,
  }, language);
}

const styleCss$5 = ".sc-ig-customer-create-popup-h{position:-webkit-sticky;position:sticky;float:right;width:34em;max-width:85%}.sc-ig-customer-create-popup-h>smoothly-icon.sc-ig-customer-create-popup{position:relative;cursor:pointer;float:right;z-index:2}.sc-ig-customer-create-popup-h>ig-customer-create.sc-ig-customer-create-popup{background-color:rgb(var(--smoothly-medium-contrast));border:solid 1px rgb(var(--smoothly-medium-shade));border-radius:0.6em;padding-left:1em;padding-right:1em;padding-top:1em;padding-bottom:0.5em;position:absolute;right:-1.4em;bottom:4.2em;z-index:2}.arrow.sc-ig-customer-create-popup{background-color:rgb(var(--smoothly-medium-contrast));border-color:rgb(var(--smoothly-medium-shade));width:30px;height:30px;border-bottom-style:solid;border-bottom-width:1px;border-right-style:solid;border-right-width:1px;position:absolute;right:0.5em;bottom:3.2em;-webkit-transform:rotate(45deg);transform:rotate(45deg);z-index:2}.sc-ig-customer-create-popup-h .background.sc-ig-customer-create-popup{position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:1}";

const IntergiroCustomerCreatePopup = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.create = createEvent(this, "create", 7);
    this.opened = false;
    this.visible = false;
  }
  componentWillLoad() {
    this.t = create$5(this.element);
  }
  onCreate(e) {
    this.create.emit(e.detail);
  }
  onClose(e) {
    this.opened = false;
  }
  render() {
    return [
      this.opened
        ? [
          h("ig-customer-create", { onClose: (e) => this.onClose(e), onCreateCustomer: (e) => this.onCreate(e) }),
          h("div", { class: "arrow" }),
          h("div", { class: "background", onClick: () => (this.opened = false) }),
        ]
        : [],
      h("smoothly-icon", { name: this.opened ? "chevron-down-circle" : "add-circle", size: "large", toolTip: this.opened ? this.t("Close") : this.t("Create customer"), onClick: () => (this.opened = !this.opened) }),
    ];
  }
  get element() { return getElement(this); }
};
IntergiroCustomerCreatePopup.style = styleCss$5;

const sv$4 = {
  "Failed to update contact information.": "Kunde inte uppdatera kontaktinformation.",
  "Updated contact information.": "Kontaktinformation uppdaterad.",
  "Updating contact information...": "Uppdaterar kontaktinformation...",
};

function create$4(language) {
  return dist.create({
    sv: sv$4,
  }, language);
}

const styleCss$4 = ".sc-ig-customer-details-h{display:table-row}.sc-ig-customer-details-h>td.sc-ig-customer-details{border-top:solid 1px rgb(var(--smoothly-medium-shade));border-bottom:solid 1px rgb(var(--smoothly-medium-shade));background-color:rgb(var(--smoothly-dark-shade));padding:0.5em}ig-subscription-table.sc-ig-customer-details,ig-orders-table.sc-ig-customer-details{margin:auto;width:90%;border:solid 1px rgb(var(--smoothly-medium-shade))}ig-customer-contact.sc-ig-customer-details{max-width:70em;margin:auto;padding:1em;padding-left:4.5em}ig-customer-balance.sc-ig-customer-details{width:75%;margin:auto}";

const IntergiroCustomerDetails = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.updateCustomers = createEvent(this, "updateCustomers", 7);
    this.opened = "";
  }
  componentWillLoad() {
    this.t = create$4(this.element);
  }
  async updateContact(event) {
    this.notice.emit(Notice.execute(this.t("Updating contact information..."), async () => {
      let result;
      this.customer.contact = event.detail;
      const response = this.customer.contact
        ? await this.client.customer.setContact(this.customer.contact, this.customer.id)
        : invalidContent("customer.contact", "No contact information available.");
      if (Error.is(response))
        result = [false, this.t("Failed to update contact information.")];
      else {
        this.updateCustomers.emit();
        result = [true, this.t("Updated contact information.")];
      }
      return result;
    }));
  }
  render() {
    let result;
    switch (this.opened) {
      case "number":
        result = (h("ig-number-details", { number: this.customer.number, identifier: this.customer.id, name: "customer" }));
        break;
      case "contact":
        result = h("ig-customer-contact", { customer: this.customer });
        break;
      case "order":
        result = h("ig-orders-table", { orders: this.orders, display: true, receipt: this.whitelist });
        break;
      case "subscription":
        result = (h("ig-subscription-table", { subscriptions: this.customer.subscription, customer: this.customer }));
        break;
      case "method":
        result = h("ig-customer-method", { client: this.client, customer: this.customer });
        break;
      case "balance":
        result = h("ig-customer-balance", { customer: this.customer, orders: this.orders });
        break;
      default:
        return "";
    }
    return h("td", { colSpan: 9 }, result);
  }
  get element() { return getElement(this); }
};
IntergiroCustomerDetails.style = styleCss$4;

const sv$3 = {
  Deselect: "Avmarkera",
  Select: "Markera",
  unknown: "okänd",
  none: "ingen",
  active: "aktiva",
  "$0 orders": "$0 ordrar",
  "Send login link via email": "Skicka inloggningslänk via e-post",
  "Successfully sent email": "E-post skickat",
  "Failed to send email": "Misslyckades med att skicka e-post",
  "The customer has no email set": "Kunden har ingen e-post satt",
  "Sending email...": "Skickar e-post...",
  daily: "daglig",
  weekly: "veckovis",
  monthly: "månadsvis",
  quarterly: "kvartalsvis",
  yearly: "årlig",
};

function create$3(language) {
  return dist.create({
    sv: sv$3,
  }, language);
}

const styleCss$3 = ".sc-ig-customer-table-row-h{display:table-row;border-top:1px solid rgba(var(--smoothly-medium-color), 0);border-bottom:1px solid rgba(var(--smoothly-medium-color), 0)}.sc-ig-customer-table-row-h:hover{-webkit-box-shadow:var(--smoothly-shadow);box-shadow:var(--smoothly-shadow);border-top-color:rgb(var(--smoothly-medium-color));border-bottom-color:rgb(var(--smoothly-medium-color))}.sc-ig-customer-table-row-h>td.sc-ig-customer-table-row>.openable.sc-ig-customer-table-row{padding:0.5em 0.3em;width:-webkit-max-content;width:-moz-max-content;width:max-content;min-width:3em;display:inline-block}.sc-ig-customer-table-row-h>td.sc-ig-customer-table-row>smoothly-checkbox.sc-ig-customer-table-row{display:inline-block;vertical-align:-40%;margin-left:0.3em}.sc-ig-customer-table-row-h>td.sc-ig-customer-table-row>div.sc-ig-customer-table-row{min-width:3em}.sc-ig-customer-table-row-h>td.sc-ig-customer-table-row>.openable.sc-ig-customer-table-row:hover{background-color:rgb(var(--smoothly-dark-shade));cursor:pointer}.sc-ig-customer-table-row-h>td.sc-ig-customer-table-row>.openable.opened.sc-ig-customer-table-row{border:solid 1px rgb(var(--smoothly-medium-shade));background-color:rgb(var(--smoothly-dark-shade));border-bottom:3px solid rgb(var(--smoothly-dark-shade));border-radius:0 0 2px 2px;margin-bottom:-2px}ig-status.sc-ig-customer-table-row{margin-right:0.2em;padding-right:0.5em;-ms-flex-negative:5;flex-shrink:5;width:100%}.sc-ig-customer-table-row-h>td.sc-ig-customer-table-row:last-child>div.sc-ig-customer-table-row{width:100%;max-width:20em;display:-ms-flexbox;display:flex;-ms-flex-line-pack:stretch;align-content:stretch;-ms-flex-wrap:nowrap;flex-wrap:nowrap}.sendLogin.sc-ig-customer-table-row{cursor:pointer;vertical-align:-40%;display:inline-block}smoothly-trigger.sc-ig-customer-table-row{border:none;padding-left:0.35em}";

const IntergiroCustomerTableRow = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.columnClicked = createEvent(this, "columnClicked", 7);
    this.customerSelected = createEvent(this, "customerSelected", 7);
    this.notice = createEvent(this, "notice", 7);
    this.opened = "";
  }
  componentWillLoad() {
    this.t = create$3(this.element);
  }
  handleColumnClick(column) {
    var _a;
    this.opened = column;
    this.columnClicked.emit({ id: (_a = this.customer) === null || _a === void 0 ? void 0 : _a.id, column });
  }
  handleSelected(e) {
    this.customerSelected.emit({ customer: this.customer, checked: !this.selected });
    e.stopPropagation();
    e.preventDefault();
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g;
    return Customer.is(this.customer)
      ? [
        h("td", null, h("smoothly-checkbox", { selected: this.selected })),
        h("td", null, h("div", { class: "openable" + (this.opened == "number" ? " opened" : ""), onClick: () => this.handleColumnClick("number") }, this.customer.number)),
        h("td", null, h("div", { class: "openable" + (this.opened == "contact" ? " opened" : ""), onClick: () => this.handleColumnClick("contact") }, (_a = Contact.getLabel(this.customer.contact)) !== null && _a !== void 0 ? _a : this.t("unknown"))),
        h("td", null, h("div", { class: "openable" + (this.opened == "order" ? " opened" : ""), onClick: () => this.handleColumnClick("order") }, this.t("$0 orders", (_c = (_b = this.orders) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0))),
        this.whitelist ? (h("td", null, h("div", { class: "openable" + (this.opened == "subscription" ? " opened" : ""), onClick: () => this.handleColumnClick("subscription") }, !this.customer.subscription || this.customer.subscription.length < 1
          ? this.t("none")
          : this.customer.subscription.length > 1
            ? this.customer.subscription.length + " " + this.t("active")
            : this.t(typeof this.customer.subscription[0].schedule == "object"
              ? this.customer.subscription[0].schedule.frequency
              : this.customer.subscription[0].schedule) +
              " " +
              Item.amount(this.customer.subscription[0].items) +
              " " +
              this.customer.subscription[0].currency))) : ([]),
        h("td", null, h("div", { class: "openable" + (this.opened == "method" ? " opened" : ""), onClick: () => this.handleColumnClick("method") }, this.customer.method[0]
          ? dist$1.format(this.customer.method[0].iin + "******" + this.customer.method[0].last4, "card-number")
          : this.t("none"))),
        this.whitelist ? (h("td", null, h("div", { class: "openable" + (this.opened == "balance" ? " opened" : ""), style: { color: this.customer.total < 0 ? "red" : "" }, onClick: () => this.handleColumnClick("balance") }, dist$1.format(this.customer.total, "price", this.customer.currency)))) : ([]),
        h("td", null, h("smoothly-trigger", { disabled: !((_d = this.customer.contact) === null || _d === void 0 ? void 0 : _d.email) }, h("smoothly-icon", { onClick: ((_e = this.customer.contact) === null || _e === void 0 ? void 0 : _e.email) ? () => this.sendLogin() : undefined, class: "sendLogin", name: "mail", size: "small", toolTip: !((_f = this.customer.contact) === null || _f === void 0 ? void 0 : _f.email)
            ? this.t("The customer has no email set")
            : this.t("Send login link via email") }))),
        h("td", null, h("div", null, h("ig-status", { status: (_g = this.customer.status) !== null && _g !== void 0 ? _g : Customer.Status.get(this.customer, this.orders ? this.orders[0] : undefined) }))),
      ]
      : null;
  }
  async sendLogin() {
    this.notice.emit(Notice.execute(this.t("Sending email..."), async () => {
      var _a;
      const response = ((_a = this.customer) === null || _a === void 0 ? void 0 : _a.id)
        ? await this.client.customer.createLink(this.customer.id)
        : backendFailure();
      return !Error.is(response)
        ? [true, this.t("Successfully sent email")]
        : [false, this.t("Failed to send email")];
    }));
  }
  get element() { return getElement(this); }
};
IntergiroCustomerTableRow.style = styleCss$3;

const sv$2 = {
  "total count: ": "totalt antal: ",
  "active: ": "aktiva: ",
  "created: ": "skapade: ",
  "inactive: ": "inaktiva: ",
  "pending: ": "väntande: ",
  "suspended: ": "avstängda: ",
};

function create$2(language) {
  return dist.create({
    sv: sv$2,
  }, language);
}

const styleCss$2 = "footer.sc-ig-customers-footer{display:block;margin:auto;border:1px solid rgb(var(--smoothly-medium-color));width:100%;max-width:90em;z-index:1;position:-webkit-sticky;position:sticky;bottom:0;color:rgb(var(--smoothly-light-contrast));background-color:rgb(var(--smoothly-light-color));padding:0.5em 0 0.5em 0em}.sc-ig-customers-footer-h>footer.sc-ig-customers-footer>td.sc-ig-customers-footer>span.sc-ig-customers-footer{display:inline-block;margin-left:0.4em;margin-right:0.6em}.sc-ig-customers-footer-h>footer.sc-ig-customers-footer>td.sc-ig-customers-footer{display:inline-block;padding-top:0.2em;margin-left:2em}";

const IntergiroCustomerFooter = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
  }
  componentWillLoad() {
    this.t = create$2(this.element);
  }
  render() {
    var _a;
    const [active, created, pending, suspended] = this.customers
      ? this.customers.reduce(([a, c, p, s], customer) => {
        var _a, _b;
        const status = (_a = customer.status) !== null && _a !== void 0 ? _a : Customer.Status.get(customer, this.orders ? (_b = this.orders[customer.id]) === null || _b === void 0 ? void 0 : _b.slice(0, 1).shift() : undefined);
        return status == "active"
          ? [++a, c, p, s]
          : status == "created"
            ? [a, ++c, p, s]
            : status == "pending"
              ? [a, c, ++p, s]
              : [a, c, p, ++s];
      }, [0, 0, 0, 0])
      : [0, 0, 0, 0];
    return (h("footer", null, h("td", null, h("span", null, this.t("total count: ")), h("span", null, this.customers ? (_a = this.customers) === null || _a === void 0 ? void 0 : _a.length : 0)), h("td", null, h("span", null, this.t("active: ")), h("span", null, active)), h("td", null, h("span", null, this.t("created: ")), h("span", null, created)), h("td", null, h("span", null, this.t("pending: ")), h("span", null, pending)), h("td", null, h("span", null, this.t("suspended: ")), h("span", null, suspended))));
  }
  get element() { return getElement(this); }
};
IntergiroCustomerFooter.style = styleCss$2;

const sv$1 = {
  "Customer number": "Kundnummer",
  Contact: "Kontakt",
  Method: "Metod",
  Orders: "Ordrar",
  Subscription: "Prenumeration",
  Balance: "Saldo",
  "Select all customers": "Markera alla kunder",
  "Deselect all customers": "Avmarkera alla kunder",
  "Loading customers from server.": "Laddar kunder från servern.",
  "There are no customers to display.": "Det finns inga kunder att visa.",
  "Load more customers": "Ladda in fler kunder",
};

function create$1(language) {
  return dist.create({
    sv: sv$1,
  }, language);
}

const styleCss$1 = ".sc-ig-customers-table-h{display:block;width:100%;max-width:90em;margin:auto;border:1px solid rgb(var(--smoothly-medium-color))}[hidden].sc-ig-customers-table-h{display:none}.sc-ig-customers-table-h>p.sc-ig-customers-table{padding-left:0.5em}.sc-ig-customers-table-h>table.sc-ig-customers-table{width:100%}.sc-ig-customers-table-h>table.sc-ig-customers-table>thead.sc-ig-customers-table>tr.sc-ig-customers-table{display:table-row;font-weight:bold;height:2em}.sc-ig-customers-table-h>table.sc-ig-customers-table>thead.sc-ig-customers-table>tr.sc-ig-customers-table>*.sc-ig-customers-table{display:table-cell;padding-right:0.5em;padding-left:0.3em;vertical-align:middle;position:-webkit-sticky;position:sticky;top:1.55cm;z-index:1;text-align:left}.sc-ig-customers-table-h>table.sc-ig-customers-table>thead.sc-ig-customers-table>tr.sc-ig-customers-table>*.sc-ig-customers-table>smoothly-icon.sc-ig-customers-table{vertical-align:-50%;margin-left:0.1em}.sc-ig-customers-table-h>table.sc-ig-customers-table>td.sc-ig-customers-table{text-align:center}.sc-ig-customers-table-h>table.sc-ig-customers-table>td.sc-ig-customers-table>button.sc-ig-customers-table>smoothly-icon.sc-ig-customers-table{cursor:pointer}";

const IntergiroCustomersTable = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.selectedChanged = createEvent(this, "selectedChanged", 7);
    this.selected = {};
    this.count = 100;
    this.opened = {};
  }
  componentWillLoad() {
    this.t = create$1(this.element);
  }
  onChecked(event) {
    this.selected = {};
    if (event.detail.selected && this.customers)
      for (const customer of this.customers)
        this.selected[customer.id] = customer;
    this.selectedChanged.emit(this.selected);
    event.stopPropagation();
    event.preventDefault();
  }
  handleToggle(event) {
    const customers = Object.assign({}, this.selected);
    if (event.detail.checked)
      customers[event.detail.customer.id] = event.detail.customer;
    else
      delete customers[event.detail.customer.id];
    this.selectedChanged.emit((this.selected = customers));
  }
  toggleColumn(e) {
    const opened = Object.assign({}, this.opened);
    if (e.detail["id"] && opened[e.detail.id] == e.detail.column)
      delete opened[e.detail.id];
    else
      opened[e.detail.id] = e.detail.column;
    this.opened = opened;
  }
  render() {
    const t = this.t;
    let result;
    if (!this.customers)
      result = h("p", null, t("Loading customers from server."));
    else if (this.customers.length <= 0)
      result = h("p", null, t("There are no customers to display."));
    else {
      result = [
        h("table", null, h("thead", null, h("tr", null, h("th", { style: { width: "5%" }, color: "light" }, h("smoothly-checkbox", { "select-all": true })), h("th", { color: "light" }, t("Customer number")), h("th", { color: "light" }, t("Contact")), h("th", { color: "light" }, t("Orders")), this.whitelist ? h("th", { color: "light" }, t("Subscription")) : [], h("th", { color: "light" }, t("Method")), this.whitelist ? h("th", { color: "light" }, t("Balance")) : [], h("th", { color: "light" }, t("Login")), h("th", { color: "light" }, t("Status")))), this.customers
          ? this.customers
            .slice(0, this.count)
            .map(customer => {
            var _a, _b;
            return [
              h("ig-customer-table-row", { customer: customer, client: this.client, whitelist: this.whitelist, orders: this.orders ? this.orders[customer.id] : undefined, opened: (_a = this.opened[customer.id]) !== null && _a !== void 0 ? _a : "", selected: this.selected.hasOwnProperty.call(this.selected, customer.id) }),
              h("ig-customer-details", { client: this.client, opened: (_b = this.opened[customer.id]) !== null && _b !== void 0 ? _b : "", orders: this.orders ? this.orders[customer.id] : undefined, whitelist: this.whitelist, customer: customer }),
            ];
          })
          : null, h("td", { colSpan: 8 }, this.count < this.customers.length && (h("button", { onClick: () => (this.count += 100) }, h("smoothly-icon", { name: "chevron-down-circle", size: "large", toolTip: this.t("Load more customers") }))))),
      ];
    }
    return result;
  }
  get element() { return getElement(this); }
};
IntergiroCustomersTable.style = styleCss$1;

const sv = {
  "Subscription number": "Prenumerationsnummer",
  Advanced: "Avancerat",
  "Create subscription": "Skapa prenumeration",
  "Start date": "Startdatum",
  "End date": "Slutdatum",
  Qty: "Antal",
  Name: "Namn",
  Price: "Pris",
  VAT: "Moms",
  daily: "Daglig",
  weekly: "Veckovis",
  monthly: "Månadsvis",
  quarterly: "Kvartalsvis",
  yearly: "Årlig",
  Day: "Dag",
  "Add item": "Lägg till artikel",
  "Creating subscription...": "Skapar prenumeration...",
  "$0 of $1 subscriptions were created.": "$0 av $1 prenumerationer skapades.",
  "Subscription was created.": "Prenumeration skapades.",
  "Failed to create $0 of $1 subscriptions.": "Kunde inte skapa $0 av $1 prenumerationer.",
  "Failed to create subscription.": "Kunde inte skapa prenumeration.",
};

function create(language) {
  return dist.create({
    sv,
  }, language);
}

const styleCss = ".sc-ig-subscription-create-h{display:block;max-width:63em}[hidden].sc-ig-subscription-create-h{display:none}smoothly-submit.sc-ig-subscription-create{max-width:-webkit-min-content;max-width:-moz-min-content;max-width:min-content}.sc-ig-subscription-create-h>form.sc-ig-subscription-create{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-direction:column;flex-direction:column}.sc-ig-subscription-create-h>form.sc-ig-subscription-create section.sc-ig-subscription-create{display:-ms-flexbox;display:flex}smoothly-trigger.sc-ig-subscription-create{border:none;position:absolute;right:4em;top:1.4em}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>main.sc-ig-subscription-create>content.sc-ig-subscription-create>*.sc-ig-subscription-create:not(.last):not(span),.sc-ig-subscription-create-h>form.sc-ig-subscription-create>section.sc-ig-subscription-create>*.sc-ig-subscription-create:not(smoothly-trigger):not(smoothly-icon){margin-bottom:0.7em;margin-left:-1px;-ms-flex-positive:1;flex-grow:1}.sc-ig-subscription-create-h>form.sc-ig-subscription-create ig-select-offset.sc-ig-subscription-create,.sc-ig-subscription-create-h>form.sc-ig-subscription-create ig-total-amount.sc-ig-subscription-create,.sc-ig-subscription-create-h>form.sc-ig-subscription-create smoothly-select.sc-ig-subscription-create,.sc-ig-subscription-create-h>form.sc-ig-subscription-create smoothly-input.sc-ig-subscription-create{border:1px solid rgb(var(--smoothly-medium-color));border-collapse:collapse}smoothly-select.sc-ig-subscription-create{display:grid}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>section.sc-ig-subscription-create>*.sc-ig-subscription-create:not(smoothly-select),.sc-ig-subscription-create-h>form.sc-ig-subscription-create ig-total-amount.sc-ig-subscription-create{-ms-flex-negative:2;flex-shrink:2}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>section.sc-ig-subscription-create>*.sc-ig-subscription-create:first-child{-ms-flex-positive:1;flex-grow:1}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>main.sc-ig-subscription-create{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>main.sc-ig-subscription-create>content.sc-ig-subscription-create{min-width:37em}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>main.sc-ig-subscription-create>content.sc-ig-subscription-create>section.sc-ig-subscription-create>smoothly-input.sc-ig-subscription-create:last-of-type{border-left:none}.sc-ig-subscription-create-h>form.sc-ig-subscription-create>main.sc-ig-subscription-create>content.sc-ig-subscription-create>section.sc-ig-subscription-create:first-of-type>*.sc-ig-subscription-create{display:-ms-flexbox;display:flex;-ms-flex-wrap:nowrap;flex-wrap:nowrap;-ms-flex-positive:1;flex-grow:1}smoothly-icon.opened.sc-ig-subscription-create{-webkit-transform:rotate(90deg);transform:rotate(90deg);-webkit-animation-duration:0.5s;animation-duration:0.5s}ig-future-due-dates.sc-ig-subscription-create{margin-left:0.5em;min-width:13em}";

const IntergiroSubscriptionCreate = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.frequency = "monthly";
    this.currency = "SEK";
    this.advanced = false;
    this.itemCount = 0;
    this.itemsVisible = false;
    this.items = [];
  }
  componentWillLoad() {
    this.t = create(this.element);
    this.subscriptionNumber = Identifier.generate(4);
    this.calculateSchedule();
  }
  componentDidRender() {
    const divisor = document.getElementById("divisor");
    const start = document.getElementById("start");
    const end = document.getElementById("end");
    const handle = (e) => {
      this.calculateSchedule();
      e.stopPropagation();
      e.preventDefault();
    };
    if (divisor)
      divisor.addEventListener("focusout", handle);
    if (start)
      start.addEventListener("focusout", handle);
    if (end)
      end.addEventListener("focusout", handle);
  }
  submitSubscription(e) {
    const subscription = {
      number: e.detail.number,
      items: this.items.length > 0 ? this.items : dist$1.parse(e.detail.price, "price", this.currency),
      currency: this.currency,
      schedule: {
        frequency: this.frequency,
        divisor: e.detail.divisor ? Schedule.extractDivisor(e.detail.divisor) : undefined,
        offset: this.offset ? Schedule.extractOffset(this.offset, this.frequency) : undefined,
      },
      start: dist$2.Date.is(e.detail.start) ? e.detail.start : undefined,
      end: dist$2.Date.is(e.detail.end) ? e.detail.end : undefined,
    };
    const idArray = Object.keys(this.customers);
    this.notice.emit(Notice.execute(this.t("Creating subscription..."), async () => {
      let result;
      const response = await Promise.all(idArray.map(id => this.client.customer.createSubscription(subscription, id)));
      const [succeeded, failed] = response.reduce(([s, f], e) => (Error.is(e) ? [s, ++f] : [++s, f]), [0, 0]);
      if (succeeded > 0)
        result = [
          true,
          idArray.length > 1
            ? this.t("$0 of $1 subscriptions were created.", succeeded, idArray.length)
            : this.t("Subscription was created."),
        ];
      else
        result = [
          false,
          idArray.length > 1
            ? this.t("Failed to create $0 of $1 subscriptions.", failed, idArray.length)
            : this.t("Failed to create subscription."),
        ];
      return result;
    }));
  }
  calculateSchedule() {
    let divisor, endDate, startDate;
    if (this.advanced) {
      const divisorInput = document.getElementById("divisor");
      divisor = hasValue(divisorInput) ? divisorInput.value : undefined;
    }
    if (document.getElementById("start") && document.getElementById("end")) {
      const start = document.getElementById("start");
      startDate = hasValue(start) && dist$2.DateTime.localize(start.value) ? start.value : dist$2.DateTime.now();
      const end = document.getElementById("end");
      endDate = hasValue(end) ? dist$2.DateTime.localize(end.value) : undefined;
    }
    this.schedule = {
      frequency: this.frequency,
      divisor: divisor ? Schedule.extractDivisor(divisor) : undefined,
      offset: this.offset ? Schedule.extractOffset(this.offset, this.frequency) : undefined,
    };
    this.dueDates = Schedule.calculateDueDates(this.schedule, 5, startDate, endDate);
  }
  onSelectionChanged(e) {
    if (e.detail.identifier == "frequency") {
      this.frequency = e.detail.value;
      this.calculateSchedule();
    }
    if (e.detail.identifier == "currency")
      this.currency = e.detail.value;
  }
  deleteItem(e) {
    const items = [];
    this.price = (Number(this.price) - Item.amount(this.items[e.detail.index])).toFixed(2);
    for (let i = 0; i < this.items.length; i++)
      if (i != e.detail.index)
        items.push(this.items[i]);
    this.items = items;
  }
  changeItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items[this.items.length - 1] = e.detail;
    this.price = Item.amount(this.items).toFixed(2);
  }
  changeOffset(e) {
    e.preventDefault();
    e.stopPropagation();
    this.offset = e.detail;
    this.calculateSchedule();
  }
  addItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items = [...this.items, {}];
    this.price = Item.amount(this.items).toFixed(2);
    this.itemCount++;
    this.itemsVisible = true;
  }
  render() {
    return [
      h("form", null, h("section", null, h("smoothly-input", { type: "text", name: "number", value: this.subscriptionNumber }, this.t("Subscription number")), h("ig-total-amount", { price: this.price, itemsvisible: this.itemCount > 1, onAddItem: (e) => this.addItem(e) }), h("smoothly-select", { identifier: "frequency", background: "transparent" }, Schedule.frequencies.map(option => (h("option", { value: option, selected: this.frequency == option }, this.t(option))))), h("smoothly-trigger", null, h("smoothly-icon", { toolTip: this.t("Advanced"), onClick: () => (this.advanced = !this.advanced), name: "arrow-forward-circle-outline", fill: "clear", size: "small", color: "medium", class: this.advanced ? "opened" : "" })), h("smoothly-submit", { color: "primary", fill: "clear", prevent: true, onSubmit: (e) => this.submitSubscription(e) }, h("smoothly-icon", { toolTip: this.t("Create subscription"), name: "add-circle", fill: "clear", size: "medium", color: "success" }))), this.advanced
        ? [
          h("section", null, h("ig-select-offset", { frequency: this.frequency, onOffsetChanged: e => this.changeOffset(e) }), h("smoothly-input", { type: "divisor", id: "divisor", name: "divisor", value: "0 / 1" }, this.t("Divisor"))),
        ]
        : [], h("main", null, h("content", null, h("section", null, h("smoothly-input", { type: "date", name: "start", id: "start", value: dist$2.DateTime.localize(dist$2.DateTime.parse(dist$2.DateTime.now())).slice(0, 10) }, this.t("Start date")), h("smoothly-input", { type: "date", name: "end", id: "end" }, this.t("End date"))), h("ig-item-list", { items: this.items.slice(0, this.items.length - 1), currency: this.currency }), this.itemsVisible ? h("ig-item-input", { key: this.itemCount, item: {} }) : []), h("ig-future-due-dates", { dates: this.dueDates }))),
    ];
  }
  get element() { return getElement(this); }
};
function hasValue(element) {
  return typeof element.value === "string";
}
IntergiroSubscriptionCreate.style = styleCss;

export { IntergiroCustomerActions as ig_customer_actions, IntergiroCustomerCreate as ig_customer_create, IntergiroCustomerCreatePopup as ig_customer_create_popup, IntergiroCustomerDetails as ig_customer_details, IntergiroCustomerTableRow as ig_customer_table_row, IntergiroCustomerFooter as ig_customers_footer, IntergiroCustomersTable as ig_customers_table, IntergiroSubscriptionCreate as ig_subscription_create };
