Spamworldpro Mini Shell
Spamworldpro


Server : Apache
System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64
User : corals ( 1002)
PHP Version : 7.4.33
Disable Function : exec,passthru,shell_exec,system
Directory :  /home/corals/ts.corals.io/frontend/plugins/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/corals/ts.corals.io/frontend/plugins/form.js
import {merge} from "lodash";
import moment from 'moment';

class Errors {
  /**
   * Create a new Errors instance.
   */
  constructor() {
    this.errors = {};
    this.defaults = {};
  }


  /**
   * Determine if an errors exists for the given field.
   *
   * @param {string} field
   */
  has(field) {
    return this.errors.hasOwnProperty(field);
  }

  /**
   * Determine if we have any errors.
   */
  any() {
    return Object.keys(this.errors).length > 0;
  }


  /**
   * Retrieve the error message for a field.
   *
   * @param {string} field
   */
  get(field) {
    if (this.errors[field]) {
      return this.errors[field][0];
    } else {
      return null;
    }
  }


  /**
   * Record the new errors.
   *
   * @param {object} errors
   */
  record(errors) {
    this.errors = errors;
  }


  /**
   * Clear one or all error fields.
   *
   * @param {string|null} field
   */
  clear(field) {
    if (field) {
      delete this.errors[field];

      return;
    }

    this.purge();
  }

  purge() {
    this.errors = {};
  }
}

class Form {
  isReady = false;
  initialized = false;

  axiosConfig = {}

  formData = [];

  config = {
    resetOnSuccess: true, fetchFormDataURL: null, model: null,
  }

  /**
   *
   * @param ctx
   * @param data
   * @param config
   */
  constructor(ctx, data, config) {
    this.originalData = data;
    this.defaults = data;

    this.ctx = ctx;

    for (let field in data) {
      this[field] = data[field];
    }

    this.errors = new Errors();

    Object.assign(this.config, config);

    this.loadFormData().then(() => {
      if (this.config.loadFormDataCallBack) {
        this.config.loadFormDataCallBack()
      }
      this.isReady = true
      this.initialized = true;
    });
  }

  async loadFormData() {
    if (!this.config.fetchFormDataURL) {
      return true;
    }

    if (this.config.model && this.ctx.$cant('create', this.config.model) && this.ctx.$cant('update', this.config.model)) {
      return true;
    }

    await this.ctx.$axios.get(this.config.fetchFormDataURL).then(({data}) => {
      let response = data.data;

      if (response.defaults) {
        this.defaults = response.defaults;
        this.setDefaults();
        delete response.defaults;
      }

      this.formData = response;
    });

    return true;
  }

  setDefaults() {
    for (let key in this.defaults) {
      this[key] = this.defaults[key];
      this.originalData[key] = this.defaults[key];
    }
  }

  getFormData(key) {
    if (!this.formData || !this.formData[key]) {
      return []
    }

    return this.formData[key];
  }

  error(field) {
    return this.errors.get(field);
  }

  state(field) {
    if (this.errors.has(field)) {
      return false;
    }

    if (!this[field] || !this[field].length) {
      return;
    }

    return true;
  }

  /**
   * Fetch all relevant data for the form.
   */
  data() {
    let formData = new FormData();

    for (let property in this.originalData) {
      let key = property;
      let propertyValue = this[property];
      if (typeof propertyValue === 'object' && propertyValue !== null && propertyValue instanceof File) {
        //Set headers in case of form has a file
        this.axiosConfig.headers = {'Content-Type': 'multipart/form-data'}
      } else if (typeof propertyValue === 'object' && propertyValue !== null) {
        if (propertyValue.constructor.name === 'Date') {
          propertyValue = moment(propertyValue).format("YYYY-MM-DD");
        } else if (Array.isArray(propertyValue) || typeof propertyValue === 'object') {
          for (let index in propertyValue) {
            let value = propertyValue[index];
            if (typeof value === 'object') {
              for (let objKey in value) {
                this.formDataAppend(formData, `${property}[${index}][${objKey}]`, value[objKey]);
              }
            } else {
              this.formDataAppend(formData, property + '[' + index + ']', value);
            }
          }
          continue;
        }
      }
      this.formDataAppend(formData, key, propertyValue);
    }

    return formData;
  }

  formDataAppend(formData, key, value) {
    if (value === null || value === undefined) {
      value = '';
    }
    formData.append(key, value);
  }

  /**
   * Reset the form fields.
   */
  reset(force = false) {
    this.errors.clear();

    if (!this.config.resetOnSuccess && !force) {
      return;
    }
    for (let field in this.originalData) {
      if (this.defaults.hasOwnProperty(field)) {
        this[field] = this.defaults[field];
        continue;
      }
      if (typeof (this[field]) == 'object') {
        this.clearObject(this[field]);
      } else {
        this[field] = '';
      }
    }
  }

  /**
   *
   * @param object
   */
  clearObject(object) {
    for (let field in object) {
      if (typeof (field) == 'object') {
        this.clearObject(object);
      } else {
        object[field] = '';
      }
    }
  }

  /**
   * Send a POST request to the given URL.
   * @param url
   * @param config
   * @returns {Promise<*>}
   */
  post(url, config = {}) {
    return this.submit('post', url, config);
  }


  /**
   * Send a PUT request to the given URL.
   * @param url
   * @param config
   * @returns {Promise<*>}
   */
  put(url, config = {}) {
    return this.submit('put', url, config);
  }


  /**
   * Send a PATCH request to the given URL.
   * @param url
   * @param config
   * @returns {Promise<*>}
   */
  patch(url, config = {}) {
    return this.submit('patch', url);
  }


  /**
   * Send a DELETE request to the given URL.
   * .
   * @param {string} url
   */
  delete(url) {
    return this.submit('delete', url);
  }


  /**
   * Submit the form.
   * @param requestType
   * @param url
   * @param config
   * @returns {Promise<unknown>}
   */
  submit(requestType, url, config = {}) {
    this.isReady = false;

    return new Promise((resolve, reject) => {
      let mergeConfig = {}

      const data = this.data()

      data.append('_method', _.lowerCase(requestType));

      merge(mergeConfig, config, this.axiosConfig)

      this.axiosConfig = {}

      this.ctx.$axios['post'](url, data, mergeConfig)
        .then(response => {
          this.onSuccess(response.data);
          this.isReady = true;
          resolve(response);
        })
        .catch(error => {
          this.onFail(error.response.data);
          this.isReady = true;
          reject(error.response);
        });
    });
  }


  /**
   * Handle a successful form submission.
   *
   * @param {object} data
   */
  onSuccess(data) {
    let message = this.getResponseMessage(data);

    if (message) {
      this.ctx.$toast.success(message);
    }

    this.reset();
  }


  /**
   * Handle a failed form submission.
   *
   * @param {object} errorData
   */
  onFail(errorData) {
    let errors = [];
    if (errorData.errors) {
      errors = errorData.errors;
    } else if (errorData.response && errorData.response.errors) {
      errors = errorData.response.errors;
    }

    let message = this.getResponseMessage(errorData);

    if (message) {
      this.ctx.$toast.error(message);
    }

    this.errors.record(errors);
  }

  getResponseMessage(data) {
    let message = '';

    if (data.message) {
      message = data.message;
    } else if (data.response && data.response.message) {
      message = data.response.message;
    }

    return message;
  }


  /**
   *
   * @param data
   */
  replace(data) {
    for (let field in data) {
      this[field] = data[field];
    }
  }

  /**
   * @param data
   * @param cloneAttr
   */
  cloneReplace(data, cloneAttr) {
    for (let [field, value] of Object.entries(cloneAttr)) {
      if (value === null) {
        this[field] = data[field]
      } else {
        this[field] = value
      }
    }
  }
}

export default (ctx, inject) => {
  inject('form', (data, config) => {
    return new Form(ctx, data, config);
  });
}

Spamworldpro Mini