Sindbad~EG File Manager

Current Path : /home/infinitibizsol/.trash/controllers.4/
Upload File :
Current File : /home/infinitibizsol/.trash/controllers.4/paymentController.js

const stripe = require("stripe")(process.env.STRIPE_SECRETE_KEY);
async function validateStripeCustomer(customerEmail) {
  try {
    // Step 1: Retrieve the customer by email
    const customers = await stripe.customers.list({
      email: customerEmail,
      limit: 1,
    });
    let customer = customers.data[0];

    // If the customer does not exist, create a new customer
    if (!customer) {
      customer = await stripe.customers.create({ email: customerEmail });
    }
    return customer;
  } catch (error) {
    console.error("Error in validateCustomer:", error.message);
    throw new Error(error.message);
  }
}
const paymentController = async (req, res) => {
  // return res.json({ message: "Success" });

  const { auctioneer_id, user_id, email, amount, name } = req.body;

  if (!auctioneer_id && !user_id) {
    return res.json({
      status: 401,
      message: "Bad Request,autioneer_id and user_id must be provided",
    });
  }

  const amountInDollars = parseInt(amount);
  const amountInCents = Math.round(amountInDollars * 100);

  try {
    let customerId;

    //Gets the customer who's email id matches the one sent by the client
    const customerList = await stripe.customers.list({
      email: email,
      limit: 1,
    });

    //Checks the if the customer exists, if not creates a new customer
    if (customerList.data.length !== 0) {
      customerId = customerList.data[0].id;
    } else {
      const customer = await stripe.customers.create({
        email: email,
        name: name,
      });
      customerId = customer.data.id;
    }

    //Creates a temporary secret key linked with the customer
    const ephemeralKey = await stripe.ephemeralKeys.create(
      { customer: customerId },
      { apiVersion: "2020-08-27" }
    );

    const paymentIntent = await stripe.paymentIntents.create({
      amount: amountInCents,
      currency: "usd",
      customer: customerId,
      // payment_method_types: ["card"],
    });
    // Step 3: Retrieve the successful PaymentIntent
    const confirmedPaymentIntent = await stripe.paymentIntents.retrieve(
      paymentIntent.id
    );
    if (confirmedPaymentIntent.status === "succeeded") {
      // Step 4: Assign the payment method as the default for the customer
      await stripe.customers.update(customerId, {
        invoice_settings: {
          default_payment_method: confirmedPaymentIntent.payment_method,
        },
      });

      // console.log(
      //   `Payment method ${confirmedPaymentIntent.payment_method} set as default for customer ${customerId}`
      // );
    }

    res.json({
      clientSecret: paymentIntent.client_secret,
      ephemeralKey: ephemeralKey.secret,
      customer: customerId,
      success: true,
    });
    // res.json({ "payment-intent": paymentIntent });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};
const getPrices = async (req, res) => {
  try {
    const prices = await stripe.prices.list();

    return res.json(prices.data);
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};
const updateDefaultPaymentMethod = async (req, res) => {
  const { email, custId, paymentMethodId } = req.body;
  try {
    let customerId;
    //Gets the customer who's email id matches the one sent by the client
    const customerList = await stripe.customers.list({
      email: email,
      limit: 1,
    });
    customerId = customerList.data[0].id;
    const results = await stripe.customers.update(custId || customerId, {
      invoice_settings: {
        default_payment_method: paymentMethodId,
      },
    });
    return res.json({ status: 200, message: "Success", data: results });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};
const deleteCanceledSubscriptionsController = async (req, res) => {
  const { customerId } = req.body;

  try {
    // Retrieve all canceled subscriptions for the customer
    const canceledSubscriptions = await stripe.subscriptions.list({
      customer: customerId,
      status: "canceled",
    });

    // Delete each canceled subscription
    const deletedSubscriptionsPromises = canceledSubscriptions.data.map(
      (subscription) => stripe.subscriptionsi.del(subscription.id)
    );

    // Wait for all deletions to complete
    const deletedSubscriptions = await Promise.all(
      deletedSubscriptionsPromises
    );

    return res.status(200).json({
      message: "Canceled subscriptions successfully deleted",
      data: deletedSubscriptions,
    });
  } catch (error) {
    console.error("Error deleting canceled subscriptions:", error.message);
    res.status(500).json({ error: error.message });
  }
};
function formatDate(timestamp) {
  const date = new Date(timestamp * 1000); // Convert to milliseconds
  return date.toISOString();
}
const createSubscriptionController = async (req, res) => {
  const { customerId, priceId, customerEmail, planAmount } = req.body;
  try {
    const current_period_start = 1712050091;
    const current_period_end = 1714642091;

    console.log(`Current Period Start: ${formatDate(current_period_start)}`);
    console.log(`Current Period End: ${formatDate(current_period_end)}`);

    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [
        {
          price_data: {
            unit_amount: planAmount * 100,
            currency: "usd",
            recurring: { interval: "month" },
            product: {
              name: "Custom Monthly Subscription",
            },
          },
        },
      ],
    });
    return res.json({ status: 200, message: "success", data: subscription });
  } catch (error) {
    return res.json(error);
  }
  /* try {
    // Step 1: Retrieve the customer by email
    const customer = await validateStripeCustomer(customerEmail);
    // Step 2: Retrieve the customer's subscriptions
    const subscriptions = await stripe.subscriptions.list({
      customer: customer.id,
      status: "active", // You could also check for 'trialing' subscriptions if applicable
      expand: ["data.default_payment_method"],
    });

    // Step 3: Check if an active subscription exists for the given price ID
    const hasActiveSubscription = subscriptions.data.some((subscription) =>
      subscription.items.data.some((item) => item.price.id === priceId)
    );

    // Step 4: Only create a new subscription if none exists for the price ID
    if (!hasActiveSubscription) {
      const subscriptionStatus = await stripe.subscriptions.create({
        customer: customer.id,
        items: [{ price: priceId }],
        expand: ["latest_invoice.payment_intent"],
      });

      return res.json({
        status: 200,
        message: "Success",
        data: subscriptionStatus,
      });
    } else {
      return res.json({
        status: 200,
        message: "Customer already has an active subscription",
      });
    }
  } catch (error) {
    return res.json({
      status: 200,
      message: error.message,
    });
  } */
};

const createCheckOut = async (req, res) => {
  const { customerId, priceId, customerEmail, line_items, mode } = req.body;
  try {
    // Step 1: Retrieve the customer by email
    const customer = await validateStripeCustomer(customerEmail);
    let session;
    //enabled-autopay
    // mode="subscription"
    if (mode.toLowerCase() === "subscription") {
      session = await stripe.checkout.sessions.create({
        mode: "subscription",
        payment_method_types: ["card"],
        line_items: [
          {
            price: priceId,
            quantity: 1,
          },
        ],
        customer: customer.id,
        // customer_email: customerEmail,
        success_url: process.env.STRIPE_SUCCESS_URL,
        cancel_url: process.env.STRIPE_CANCEL_URL,
      });
    }
    //dont-enabled-autopay
    // mode="payment"
    else {
      session = await stripe.checkout.sessions.create({
        mode: "payment",
        payment_method_types: ["card"],
        line_items: [line_items],
        customer: customer.id,
        // customer_email: customerEmail,
        success_url: process.env.STRIPE_SUCCESS_URL,
        cancel_url: process.env.STRIPE_CANCEL_URL,
      });
    }

    // console.log(session);
    return res.status(200).json({ data: session });
  } catch (error) {
    return res.json({
      status: 200,
      message: error.message,
    });
  }
};

const customerPortal = async (req, res) => {
  const { customerId, priceId, customerEmail } = req.body;
  try {
    // Step 1: Retrieve the customer by email
    const customer = await validateStripeCustomer(customerEmail);
    const portalSession = await stripe.billingPortal.sessions.create({
      customer: customer.id,
      return_url: process.env.STRIPE_SUCCESS_URL,
    });
    // console.log(portalSession);
    return res.status(200).json({ data: portalSession.url });
  } catch (error) {
    return res.json({
      status: 200,
      message: error.message,
    });
  }
};

const getSubscriptionDetails = async (req, res) => {
  try {
    const { customerId, email } = req.body;
    let customer_Id;
    const customerList = await stripe.customers.list({
      email: email,
      limit: 1,
    });

    customer_Id = customerId || customerList.data[0].id;

    const subscriptions = await stripe.subscriptions.list({
      customer: customer_Id,
      status: "all",
      expand: ["data.default_payment_method"],
    });
    // return res.json(subscriptions);
    let customResponses = subscriptions.data.map((subItem) => {
      const billing_details = subItem.default_payment_method.billing_details;
      const card = subItem.default_payment_method.card;
      const plan = subItem.plan;
      // Determine autoPay based on subscription status and whether it is set to cancel at period end.
      const autoPayEnabled =
        ["active", "trialing"].includes(subItem.status) &&
        !subItem.cancel_at_period_end;

      return {
        card_holder: billing_details.name, // Still a placeholder for product ID
        card_brand: card.brand, // Still a placeholder for product ID
        exp_month: card.exp_month,
        exp_year: card.exp_year,
        last4: card.last4,
        product_name: plan.nickname, // Still a placeholder for product ID
        product_price: plan.amount / 100,
        last_charge_dt: subItem.current_period_start
          ? new Date(subItem.current_period_start * 1000).toLocaleDateString()
          : "Not Set",
        next_payment_dt: autoPayEnabled
          ? new Date(subItem.current_period_end * 1000).toLocaleDateString()
          : "Not Set", // Only set if autoPay is true
        autoPay: autoPayEnabled,
      };
    });
    res.json({ status: 200, message: "Success", data: customResponses });
  } catch (error) {
    console.error("Error fetching subscription details:", error);
    res
      .status(500)
      .json({ status: 500, message: "Internal Server Error", data: [] });
  }
};

const disabledAutoPayment = async (req, res) => {
  const { customerId, productId } = req.body;
  try {
    // Retrieve all subscriptions for the specified customer
    const subscriptions = await stripe.subscriptions.list({
      customer: customerId,
      status: "active",
    });

    // Filter subscriptions that contain the product you want to disable autopay for
    let targetedSubscriptions = subscriptions.data.filter((subscription) =>
      subscription.items.data.some((item) => item.price.product === productId)
    );

    // Update each targeted subscription to cancel at the period end
    for (const subscription of targetedSubscriptions) {
      await stripe.subscriptions.update(subscription.id, {
        cancel_at_period_end: true,
      });
      // console.log(
      //   `Autopayment has been disabled for subscription: ${subscription.id}`
      // );
    }

    return res.json({
      status: 200,
      message: "Success",
      data: targetedSubscriptions,
    });
  } catch (error) {
    // Log an error if it occurs
    console.error("Error disabling autopayment for customer product:", error);
  }
};

const createCustomer = async (req, res) => {
  try {
    const customer = await stripe.customers.create({
      name: req.body.name,
      email: req.body.email,
    });

    res.status(200).send(customer);
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

const attachPaymentMethod = async (req, res) => {
  try {
    const { email, name, pamentMethodId } = req.body;
    let customerId;
    if (!req.body.email || req.body.email === "") {
      return res.json({ status: 401, message: "please provide email" });
    }
    const customerList = await stripe.customers.list({
      email: req.body.email,
      limit: 1,
    });

    //Checks the if the customer exists, if not creates a new customer
    if (customerList.data.length !== 0) {
      customerId = customerList.data[0].id;
    } else {
      const customer = await stripe.customers.create({
        email: email,
        name: name,
      });
      if (customer) {
        customerId = customer.id;
      } else {
        return res.json({ status: 402, message: "Something went wrong" });
      }
    }
    // return res.json(customerId);
    const paymentMethod = await stripe.paymentMethods.attach(pamentMethodId, {
      customer: customerId,
    });
    // Set it as the default payment method
    await stripe.customers.update(customerId, {
      invoice_settings: {
        default_payment_method: pamentMethodId,
      },
    });
    res.status(200).send({ PaymentMethod: paymentMethod });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

const detachPaymentMethod = async (req, res) => {
  try {
    const { paymentMethodId } = req.body;

    if (!paymentMethodId) {
      return res.json({
        status: 200,
        message: "Please provide PaymentMethodId",
      });
    }

    const detachedPaymentMethod = await stripe.paymentMethods.detach(
      `${paymentMethodId}`
    );
    // console.log(detachedPaymentMethod);
    return res.json({
      success: true,
      message: "Payment method detached successfully.",
      data: detachedPaymentMethod,
    });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

const createCharges = async (req, res) => {
  try {
    const createCharge = await stripe.charges.create({
      receipt_email: "tester@gmail.com",
      amount: parseInt(req.body.amount) * 100, //amount*100
      currency: "usd",
      card: req.body.card_id,
      customer: req.body.customer_id,
    });

    res.status(200).send(createCharge);
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

const PaymentMethods = async (req, res) => {
  try {
    let customerId;
    if (!req.body.email || req.body.email === "") {
      return res.json({ status: 401, message: "please provide email" });
    }
    const customerList = await stripe.customers.list({
      email: req.body.email,
      limit: 1,
    });

    //Checks the if the customer exists, if not creates a new customer
    if (customerList.data.length <= 0) {
      return res.json({ status: 400, message: "Customer Not Found" });
    }
    customerId = customerList.data[0].id;
    const paymentMethods = await stripe.customers.listPaymentMethods(
      `${customerId}`,
      { type: "card" }
    );
    const cardsList = paymentMethods.data.map((item) => {
      return {
        payemen_method_id: item.id,
        customer_id: item.customer,
        card: item.card,
      };
    });
    res.json({ status: 200, message: "Success", data: cardsList });
  } catch (error) {
    return res.status(500).json({
      status: 500,
      message: "Internal Server Error",
      error: error.message,
    });
  }
};

module.exports = {
  paymentController,
  createCustomer,
  attachPaymentMethod,
  createCharges,
  PaymentMethods,
  detachPaymentMethod,
  createSubscriptionController,
  updateDefaultPaymentMethod,
  getSubscriptionDetails,
  disabledAutoPayment,
  deleteCanceledSubscriptionsController,
  getPrices,
  createCheckOut,
  customerPortal,
};

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists