{% extends "base.html" %} {% from "macros.jinja" import window_vars with context
%} {% block page %}
<div class="row q-col-gutter-md">
  <div class="col-12 col-md-7 q-gutter-y-md">
    <q-card>
      <q-card-section>
        {% raw %}
        <q-btn
          unelevated
          color="deep-purple"
          @click="formDialogCharge.show = true"
          >New charge
        </q-btn>
      </q-card-section>
    </q-card>

    <q-card>
      <q-card-section>
        <div class="row items-center no-wrap q-mb-md">
          <div class="col">
            <h5 class="text-subtitle1 q-my-none">Charges</h5>
          </div>

          <div class="col-auto">
            <q-input
              borderless
              dense
              debounce="300"
              v-model="filter"
              placeholder="Search"
            >
              <template v-slot:append>
                <q-icon name="search"></q-icon>
              </template>
            </q-input>
            <q-btn flat color="grey" @click="exportchargeCSV"
              >Export to CSV</q-btn
            >
          </div>
        </div>
        <q-table
          flat
          dense
          :data="ChargeLinks"
          row-key="id"
          :columns="ChargesTable.columns"
          :pagination.sync="ChargesTable.pagination"
          :filter="filter"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width></q-th>
              <q-th auto-width></q-th>

              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                auto-width
              >
                <div v-if="col.name == 'id'"></div>
                <div v-else>{{ col.label }}</div>
              </q-th>
              <q-th auto-width></q-th>
            </q-tr>
          </template>

          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  unelevated
                  dense
                  size="xs"
                  icon="link"
                  :color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
                  type="a"
                  :href="props.row.displayUrl"
                  target="_blank"
                >
                  <q-tooltip> Payment link </q-tooltip>
                </q-btn>
              </q-td>
              <q-td auto-width>
                <q-btn
                  v-if="props.row.time_elapsed && props.row.balance < props.row.amount"
                  unelevated
                  flat
                  dense
                  size="xs"
                  icon="error"
                  :color="($q.dark.isActive) ? 'red' : 'red'"
                >
                  <q-tooltip> Time elapsed </q-tooltip>
                </q-btn>

                <q-btn
                  v-else-if="props.row.balance >= props.row.amount"
                  unelevated
                  flat
                  dense
                  size="xs"
                  icon="check"
                  :color="($q.dark.isActive) ? 'green' : 'green'"
                >
                  <q-tooltip> PAID! </q-tooltip>
                </q-btn>

                <q-btn
                  v-else
                  unelevated
                  dense
                  size="xs"
                  icon="cached"
                  flat
                  :color="($q.dark.isActive) ? 'blue' : 'blue'"
                >
                  <q-tooltip> Processing </q-tooltip>
                </q-btn>
                <q-btn
                  flat
                  dense
                  size="xs"
                  @click="deleteChargeLink(props.row.id)"
                  icon="cancel"
                  color="pink"
                >
                  <q-tooltip> Delete charge </q-tooltip>
                </q-btn>
              </q-td>
              <q-td
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                auto-width
              >
                <div v-if="col.name == 'id'"></div>
                <div v-else>{{ col.value }}</div>
              </q-td>
            </q-tr>
          </template>
          {% endraw %}
        </q-table>
      </q-card-section>
    </q-card>
  </div>

  <div class="col-12 col-md-5 q-gutter-y-md">
    <q-card>
      <q-card-section>
        <h6 class="text-subtitle1 q-my-none">LNbits satspay Extension</h6>
      </q-card-section>
      <q-card-section class="q-pa-none">
        <q-separator></q-separator>
        <q-list> {% include "satspay/_api_docs.html" %} </q-list>
      </q-card-section>
    </q-card>
  </div>
  <q-dialog
    v-model="formDialogCharge.show"
    position="top"
    @hide="closeFormDialog"
  >
    <q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
      <q-form @submit="sendFormDataCharge" class="q-gutter-md">
        <q-input
          filled
          dense
          v-model.trim="formDialogCharge.data.description"
          type="text"
          label="*Description"
        ></q-input>

        <q-input
          filled
          dense
          v-model.trim="formDialogCharge.data.amount"
          type="number"
          label="*Amount (sats)"
        ></q-input>

        <q-input
          filled
          dense
          v-model.trim="formDialogCharge.data.time"
          type="number"
          max="1440"
          label="*Mins valid for (max 1440)"
        >
        </q-input>

        <q-input
          filled
          dense
          v-model.trim="formDialogCharge.data.webhook"
          type="url"
          label="Webhook (URL to send transaction data to once paid)"
        >
        </q-input>

        <q-input
          filled
          dense
          v-model.trim="formDialogCharge.data.completelink"
          type="url"
          label="Completed button URL"
        >
        </q-input>
        <q-input
          filled
          dense
          v-model.trim="formDialogCharge.data.completelinktext"
          type="text"
          label="Completed button text (ie 'Back to merchant')"
        >
        </q-input>

        <div class="row">
          <div class="col">
            <div v-if="walletLinks.length > 0">
              <q-checkbox
                v-model="formDialogCharge.data.onchain"
                label="Onchain"
              />
            </div>
            <div v-else>
              <q-checkbox :value="false" label="Onchain" disabled>
                <q-tooltip>
                  Watch-Only extension MUST be activated and have a wallet
                </q-tooltip>
              </q-checkbox>
            </div>
          </div>
          <div class="col">
            <div>
              <q-checkbox
                v-model="formDialogCharge.data.lnbits"
                label="LNbits wallet"
              />
            </div>
          </div>
        </div>

        <div v-if="formDialogCharge.data.onchain">
          <q-select
            filled
            dense
            emit-value
            v-model="formDialogCharge.data.onchainwallet"
            :options="walletLinks"
            label="Onchain Wallet"
          />
        </div>

        <q-select
          v-if="formDialogCharge.data.lnbits"
          filled
          dense
          emit-value
          v-model="formDialogCharge.data.lnbitswallet"
          :options="g.user.walletOptions"
          label="Wallet *"
        >
        </q-select>
        <div class="row q-mt-lg">
          <q-btn
            unelevated
            color="deep-purple"
            :disable="
                formDialogCharge.data.time == null ||
                formDialogCharge.data.amount == null"
            type="submit"
            >Create Charge</q-btn
          >
          <q-btn @click="cancelCharge" flat color="grey" class="q-ml-auto"
            >Cancel</q-btn
          >
        </div>
      </q-form>
    </q-card>
  </q-dialog>
</div>
{% endblock %} {% block scripts %} {{ window_vars(user) }}
<script src="{{ url_for('static', filename='vendor/vue-qrcode@1.0.2/vue-qrcode.min.js') }}"></script>
<style></style>
<script>
  Vue.component(VueQrcode.name, VueQrcode)

  var mapCharge = obj => {
    obj._data = _.clone(obj)
    obj.theTime = obj.time * 60 - (Date.now() / 1000 - obj.timestamp)
    obj.time = obj.time + 'mins'

    if (obj.time_elapsed) {
      obj.date = 'Time elapsed'
    } else {
      obj.date = Quasar.utils.date.formatDate(
        new Date((obj.theTime - 3600) * 1000),
        'HH:mm:ss'
      )
    }
    obj.displayUrl = ['/satspay/', obj.id].join('')
    return obj
  }

  new Vue({
    el: '#vue',
    mixins: [windowMixin],
    data: function () {
      return {
        filter: '',
        watchonlyactive: false,
        balance: null,
        checker: null,
        walletLinks: [],
        ChargeLinks: [],
        ChargeLinksObj: [],
        onchainwallet: '',
        currentaddress: '',
        Addresses: {
          show: false,
          data: null
        },
        mempool: {
          endpoint: ''
        },

        ChargesTable: {
          columns: [
            {
              name: 'theId',
              align: 'left',
              label: 'ID',
              field: 'id'
            },
            {
              name: 'description',
              align: 'left',
              label: 'Title',
              field: 'description'
            },
            {
              name: 'timeleft',
              align: 'left',
              label: 'Time left',
              field: 'date'
            },
            {
              name: 'time to pay',
              align: 'left',
              label: 'Time to Pay',
              field: 'time'
            },
            {
              name: 'amount',
              align: 'left',
              label: 'Amount to pay',
              field: 'amount'
            },
            {
              name: 'balance',
              align: 'left',
              label: 'Balance',
              field: 'balance'
            },
            {
              name: 'onchain address',
              align: 'left',
              label: 'Onchain Address',
              field: 'onchainaddress'
            },
            {
              name: 'LNbits wallet',
              align: 'left',
              label: 'LNbits wallet',
              field: 'lnbitswallet'
            },
            {
              name: 'Webhook link',
              align: 'left',
              label: 'Webhook link',
              field: 'webhook'
            },
            {
              name: 'Paid link',
              align: 'left',
              label: 'Paid link',
              field: 'completelink'
            }
          ],
          pagination: {
            rowsPerPage: 10
          }
        },
        formDialog: {
          show: false,
          data: {}
        },
        formDialogCharge: {
          show: false,
          data: {
            onchain: false,
            lnbits: false,
            description: '',
            time: null,
            amount: null
          }
        },
        qrCodeDialog: {
          show: false,
          data: null
        }
      }
    },
    methods: {
      cancelCharge: function (data) {
        var self = this
        self.formDialogCharge.data.description = ''
        self.formDialogCharge.data.onchainwallet = ''
        self.formDialogCharge.data.lnbitswallet = ''
        self.formDialogCharge.data.time = null
        self.formDialogCharge.data.amount = null
        self.formDialogCharge.data.webhook = ''
        self.formDialogCharge.data.completelink = ''
        self.formDialogCharge.show = false
      },

      getWalletLinks: function () {
        var self = this

        LNbits.api
          .request(
            'GET',
            '/watchonly/api/v1/wallet',
            this.g.user.wallets[0].inkey
          )
          .then(function (response) {
            for (i = 0; i < response.data.length; i++) {
              self.walletLinks.push(response.data[i].id)
            }
            return
          })
          .catch(function (error) {
            LNbits.utils.notifyApiError(error)
          })
      },
      closeFormDialog: function () {
        this.formDialog.data = {
          is_unique: false
        }
      },
      openQrCodeDialog: function (linkId) {
        var self = this
        var getAddresses = this.getAddresses
        getAddresses(linkId)
        self.current = linkId
        self.Addresses.show = true
      },
      getCharges: function () {
        var self = this
        var getAddressBalance = this.getAddressBalance

        LNbits.api
          .request(
            'GET',
            '/satspay/api/v1/charges',
            this.g.user.wallets[0].inkey
          )
          .then(function (response) {
            self.ChargeLinks = response.data.map(mapCharge)
          })
          .catch(function (error) {
            LNbits.utils.notifyApiError(error)
          })
      },
      sendFormDataCharge: function () {
        var self = this
        var wallet = this.g.user.wallets[0].adminkey
        var data = this.formDialogCharge.data
        data.amount = parseInt(data.amount)
        data.time = parseInt(data.time)
        this.createCharge(wallet, data)
      },
      timerCount: function () {
        self = this
        var refreshIntervalId = setInterval(function () {
          for (i = 0; i < self.ChargeLinks.length - 1; i++) {
            if (self.ChargeLinks[i]['paid'] == 'True') {
              setTimeout(function () {
                LNbits.api
                  .request(
                    'GET',
                    '/satspay/api/v1/charges/balance/' +
                      self.ChargeLinks[i]['id'],
                    'filla'
                  )
                  .then(function (response) {})
              }, 2000)
            }
          }
          self.getCharges()
        }, 20000)
      },
      createCharge: function (wallet, data) {
        var self = this

        LNbits.api
          .request('POST', '/satspay/api/v1/charge', wallet, data)
          .then(function (response) {
            self.ChargeLinks.push(mapCharge(response.data))
            self.formDialogCharge.show = false
          })
          .catch(function (error) {
            LNbits.utils.notifyApiError(error)
          })
      },

      deleteChargeLink: function (chargeId) {
        var self = this
        var link = _.findWhere(this.ChargeLinks, {id: chargeId})
        LNbits.utils
          .confirmDialog('Are you sure you want to delete this pay link?')
          .onOk(function () {
            LNbits.api
              .request(
                'DELETE',
                '/satspay/api/v1/charge/' + chargeId,
                self.g.user.wallets[0].adminkey
              )
              .then(function (response) {
                self.ChargeLinks = _.reject(self.ChargeLinks, function (obj) {
                  return obj.id === chargeId
                })
              })
              .catch(function (error) {
                LNbits.utils.notifyApiError(error)
              })
          })
      },
      exportchargeCSV: function () {
        var self = this
        LNbits.utils.exportCSV(self.ChargesTable.columns, this.ChargeLinks)
      }
    },
    created: function () {
      var self = this
      var getCharges = this.getCharges
      getCharges()
      var getWalletLinks = this.getWalletLinks
      getWalletLinks()
      var timerCount = this.timerCount
      timerCount()
    }
  })
</script>
{% endblock %}
