Initial commit
This commit is contained in:
commit
1947c9659c
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,87 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 3 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 6 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# RUN FLASK
|
||||
# =============================
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 3 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 6 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 3 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 6 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 3 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 3 BULAN
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
# tambahkan regressor
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
# =============================
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# =============================
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
# =============================
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# =============================
|
||||
# ROUTE TEST
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
# =============================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# ROUTE TEST
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# =============================
|
||||
# LOAD MODEL
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# ROUTE TEST
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
# LOAD MODEL
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# ROUTE TEST
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
from flask import Flask, jsonify
|
||||
import pickle
|
||||
import pandas as pd
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# LOAD MODEL
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model PeGas berhasil dimuat")
|
||||
|
||||
# ROUTE TEST
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({
|
||||
"status": "API PeGas aktif"
|
||||
})
|
||||
|
||||
|
||||
# PREDIKSI 30 HARI
|
||||
|
||||
@app.route("/predict_30days")
|
||||
def predict_30days():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=30)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 3 BULAN
|
||||
|
||||
@app.route("/predict_3months")
|
||||
def predict_3months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=90)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
|
||||
# PREDIKSI 6 BULAN
|
||||
|
||||
@app.route("/predict_6months")
|
||||
def predict_6months():
|
||||
|
||||
future = model_pegas.make_future_dataframe(periods=180)
|
||||
|
||||
future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
forecast = model_pegas.predict(future)
|
||||
|
||||
result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)
|
||||
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
# RUN FLASK
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# ======================
|
||||
# PREPROCESSING
|
||||
# ======================
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# ======================
|
||||
# REGRESSOR
|
||||
# ======================
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# ======================
|
||||
# HITUNG RASIO
|
||||
# ======================
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# ======================
|
||||
# PREDIKSI
|
||||
# ======================
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# ======================
|
||||
# PREPROCESSING
|
||||
# ======================
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# ======================
|
||||
# REGRESSOR
|
||||
# ======================
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# ======================
|
||||
# HITUNG RASIO
|
||||
# ======================
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# ======================
|
||||
# PREDIKSI
|
||||
# ======================
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# ======================
|
||||
# PREPROCESSING
|
||||
# ======================
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# ======================
|
||||
# REGRESSOR
|
||||
# ======================
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# ======================
|
||||
# HITUNG RASIO
|
||||
# ======================
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# ======================
|
||||
# PREDIKSI
|
||||
# ======================
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# ======================
|
||||
# PREPROCESSING
|
||||
# ======================
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# ======================
|
||||
# REGRESSOR
|
||||
# ======================
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# ======================
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# ======================
|
||||
# PREPROCESSING
|
||||
# ======================
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# ======================
|
||||
# REGRESSOR
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# ======================
|
||||
# PREPROCESSING
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# REGRESSOR
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
# ======================
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# PREPROCESSING
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# REGRESSOR
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# ======================
|
||||
# LOAD DATA
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# PREPROCESSING
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# REGRESSOR
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# ======================
|
||||
# LOAD MODEL
|
||||
# ======================
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# LOAD DATA
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# PREPROCESSING
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# REGRESSOR
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
import pickle
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_absolute_error
|
||||
|
||||
# LOAD MODEL
|
||||
|
||||
with open("model_pegas.pkl", "rb") as f:
|
||||
model_pegas = pickle.load(f)
|
||||
|
||||
print("Model berhasil dimuat")
|
||||
|
||||
# LOAD DATA
|
||||
|
||||
df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
|
||||
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")
|
||||
|
||||
# PREPROCESSING
|
||||
|
||||
df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
|
||||
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])
|
||||
|
||||
df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
|
||||
|
||||
# REGRESSOR
|
||||
|
||||
df_gab_w['is_pengetatan'] = (df_gab_w['ds'] >= '2025-10-01').astype(int)
|
||||
|
||||
# HITUNG RASIO
|
||||
|
||||
overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))
|
||||
|
||||
ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()
|
||||
|
||||
print("Rasio:", ratio)
|
||||
|
||||
# PREDIKSI
|
||||
|
||||
forecast = model_pegas.predict(df_gab_w)
|
||||
|
||||
eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')
|
||||
|
||||
y_true = eval_df['y'].values
|
||||
y_pred_scaled = eval_df['yhat'].values * ratio
|
||||
|
||||
# EVALUASI
|
||||
|
||||
mae = mean_absolute_error(y_true, y_pred_scaled)
|
||||
|
||||
mape = np.mean(
|
||||
np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
|
||||
) * 100
|
||||
|
||||
print("----------------------------")
|
||||
print("HASIL EVALUASI MODEL PEGAS")
|
||||
print("MAE :", round(mae,2), "tabung")
|
||||
print("MAPE:", round(mape,2), "%")
|
||||
print("----------------------------")
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
from flask import Flask, jsonify, request
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from prophet import Prophet
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Nilai scale hasil pengujian grid search pada data pangkalan.
|
||||
# Scale 0.4 dipilih karena menghasilkan nilai MAPE terkecil dibanding nilai scale lainnya.
|
||||
# Nilai ini merepresentasikan bahwa setelah regulasi Oktober 2025, rata-rata penjualan
|
||||
# pangkalan menjadi 40% dari kondisi sebelum regulasi.
|
||||
PENGETATAN_SCALE = 0.4
|
||||
|
||||
# Threshold penurunan untuk mendeteksi apakah pangkalan terdampak pengetatan.
|
||||
# Nilai 0.4 (40%) diperoleh dari data aktual pangkalan Eka yang menunjukkan
|
||||
# penurunan sebesar 40% dari September 2025 (358 tabung) ke Oktober 2025 (215 tabung)
|
||||
# akibat regulasi pengetatan distribusi LPG dari agen.
|
||||
PENGETATAN_THRESHOLD = 0.4
|
||||
|
||||
@app.route("/")
|
||||
def home():
|
||||
return jsonify({"status": "API PeGas Aktif", "mode": "Adaptive Local Scaling"})
|
||||
|
||||
@app.route("/predict", methods=['POST'])
|
||||
def predict():
|
||||
try:
|
||||
data = request.json
|
||||
|
||||
# 1. AMBIL PARAMETER DARI LARAVEL
|
||||
days = int(data.get('days', 30)) # jumlah hari prediksi (default 30)
|
||||
user_data_raw = data.get('user_data', []) # data dari Laravel
|
||||
|
||||
# 2. PREPROCESSING DATA
|
||||
df_user = pd.DataFrame(user_data_raw)
|
||||
|
||||
df_user['ds'] = pd.to_datetime(df_user['tanggal']) # ubah ke datetime
|
||||
df_user['y'] = df_user['jumlah'] # target
|
||||
|
||||
df_user = df_user[['ds', 'y']].sort_values('ds') # urutkan berdasarkan tanggal
|
||||
|
||||
# 3. DETEKSI APAKAH PANGKALAN TERDAMPAK PENGETATAN
|
||||
# Hitung rata-rata penjualan sebelum dan sesudah Oktober 2025
|
||||
before = df_user[df_user['ds'] < '2025-10-01']['y'].mean() # rata-rata sebelum Oktober 2025
|
||||
after = df_user[df_user['ds'] >= '2025-10-01']['y'].mean() # rata-rata setelah Oktober 2025
|
||||
|
||||
# Cek apakah data lengkap dan terjadi penurunan signifikan
|
||||
# Pangkalan dianggap terdampak jika penurunan setelah Oktober 2025
|
||||
# mencapai 40% atau lebih dari kondisi sebelumnya, sesuai data aktual pangkalan.
|
||||
# Jika data sebelum atau sesudah Oktober 2025 tidak tersedia (NaN),
|
||||
# atau before bernilai 0 (menghindari pembagian nol), maka dianggap tidak terdampak.
|
||||
if pd.isna(before) or pd.isna(after) or before == 0:
|
||||
terdampak = False # data tidak lengkap, anggap kondisi normal
|
||||
else:
|
||||
penurunan = (before - after) / before # hitung persentase penurunan
|
||||
terdampak = penurunan >= PENGETATAN_THRESHOLD # terdampak jika turun >= 40%
|
||||
|
||||
print(f">>> Penurunan: {round(penurunan * 100, 1) if not pd.isna(before) and before != 0 else 'N/A'}%")
|
||||
print(f">>> Terdampak pengetatan: {terdampak}")
|
||||
|
||||
# 4. BUAT REGRESSOR PENGETATAN
|
||||
# Penambahan variabel pengetatan_level sebagai regressor tambahan untuk
|
||||
# memberitahu model bahwa terdapat perubahan kondisi distribusi sejak Oktober 2025.
|
||||
# Nilai 1.0 merepresentasikan kondisi normal sebelum Oktober 2025.
|
||||
# Nilai PENGETATAN_SCALE (0.4) hanya diterapkan jika pangkalan terdeteksi terdampak,
|
||||
# konsisten dengan nilai yang digunakan pada saat pelatihan dan evaluasi model.
|
||||
df_user['pengetatan_level'] = 1.0 # default kondisi normal
|
||||
if terdampak:
|
||||
df_user.loc[df_user['ds'] >= '2025-10-01', 'pengetatan_level'] = PENGETATAN_SCALE
|
||||
print(f">>> Scale pengetatan diterapkan: {PENGETATAN_SCALE}")
|
||||
else:
|
||||
print(f">>> Pangkalan tidak terdampak pengetatan, scale tidak diterapkan")
|
||||
|
||||
# 5. MODEL PROPHET
|
||||
# Konfigurasi seasonality disesuaikan dengan karakteristik data penjualan LPG:
|
||||
# - weekly_seasonality diaktifkan karena pola penjualan dipengaruhi jadwal pengiriman mingguan
|
||||
model = Prophet(
|
||||
yearly_seasonality=False,
|
||||
weekly_seasonality=True,
|
||||
daily_seasonality=False
|
||||
)
|
||||
|
||||
# Tambahkan regressor pengetatan agar model mengetahui adanya perubahan kondisi eksternal.
|
||||
# Regressor harus ditambahkan sebelum model.fit().
|
||||
model.add_regressor('pengetatan_level')
|
||||
|
||||
# 6. TRAIN MODEL
|
||||
model.fit(df_user) # latih model menggunakan seluruh data historis pengguna
|
||||
|
||||
# 7. FUTURE DATAFRAME
|
||||
future = model.make_future_dataframe(periods=days) # buat daftar tanggal yang akan diprediksi
|
||||
|
||||
# Isi nilai regressor untuk tanggal masa depan.
|
||||
# Nilai pengetatan_level harus diketahui untuk seluruh tanggal prediksi,
|
||||
# sesuai dengan ketentuan penggunaan additional regressor pada Prophet.
|
||||
future['pengetatan_level'] = 1.0 # default kondisi normal
|
||||
if terdampak:
|
||||
future.loc[future['ds'] >= '2025-10-01', 'pengetatan_level'] = PENGETATAN_SCALE
|
||||
|
||||
# 8. PREDIKSI
|
||||
forecast = model.predict(future) # prediksi masa depan dengan mempertimbangkan kondisi pengetatan
|
||||
|
||||
# 9. HARI MINGGU = 0 (ATURAN BISNIS NYATA / agen libur pengiriman)
|
||||
# Setelah prediksi dihasilkan, dilakukan koreksi bahwa hari Minggu bernilai 0
|
||||
# karena agen tidak melakukan pengiriman pada hari tersebut.
|
||||
forecast['ds_dt'] = pd.to_datetime(forecast['ds'])
|
||||
is_sunday = forecast['ds_dt'].dt.dayofweek == 6 # 6 = hari Minggu
|
||||
|
||||
forecast.loc[is_sunday, ['yhat', 'yhat_upper', 'yhat_lower']] = 0
|
||||
|
||||
# 10. AMBIL HASIL AKHIR
|
||||
result = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(days).copy()
|
||||
|
||||
# 11. POST-PROCESSING sebelum dikirim ke Laravel
|
||||
|
||||
# Tidak boleh negatif karena penjualan LPG tidak mungkin bernilai minus
|
||||
result['yhat'] = result['yhat'].clip(lower=0)
|
||||
result['yhat_lower'] = result['yhat_lower'].clip(lower=0)
|
||||
result['yhat_upper'] = result['yhat_upper'].clip(lower=0)
|
||||
|
||||
# Pembulatan karena satuan adalah tabung LPG yang tidak mungkin bernilai desimal
|
||||
result['yhat'] = result['yhat'].round(0).astype(int)
|
||||
result['yhat_lower'] = result['yhat_lower'].round(0).astype(int)
|
||||
result['yhat_upper'] = result['yhat_upper'].round(0).astype(int)
|
||||
|
||||
# Format tanggal ke string agar bisa dikirim sebagai JSON ke Laravel
|
||||
result['ds'] = result['ds'].dt.strftime('%Y-%m-%d')
|
||||
|
||||
# Kirim hasil prediksi ke Laravel dalam format JSON
|
||||
return jsonify(result.to_dict(orient="records"))
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error pada server Flask: {str(e)}")
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True, port=5000)
|
||||
Binary file not shown.
|
|
@ -0,0 +1,18 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[docker-compose.yml]
|
||||
indent_size = 4
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
APP_NAME=PeGas
|
||||
APP_ENV=local
|
||||
APP_KEY=base64:3JcVBJ3mOEnfJslDZqoSmTgpgBZyNSAohuIqpawl5aY=
|
||||
APP_DEBUG=true
|
||||
APP_URL= localhost
|
||||
FLASK_URL=http://127.0.0.1:5000
|
||||
# FLASK_URL=https://substernal-collaboratively-betty.ngrok-free.dev/python/eka
|
||||
|
||||
|
||||
APP_LOCALE=en
|
||||
APP_FALLBACK_LOCALE=en
|
||||
APP_FAKER_LOCALE=en_US
|
||||
|
||||
APP_MAINTENANCE_DRIVER=file
|
||||
# APP_MAINTENANCE_STORE=database
|
||||
|
||||
PHP_CLI_SERVER_WORKERS=4
|
||||
|
||||
BCRYPT_ROUNDS=12
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_STACK=single
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=pegas
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_ENCRYPT=false
|
||||
SESSION_PATH=/
|
||||
SESSION_DOMAIN=null
|
||||
|
||||
BROADCAST_CONNECTION=log
|
||||
FILESYSTEM_DISK=local
|
||||
QUEUE_CONNECTION=database
|
||||
|
||||
CACHE_STORE=file
|
||||
# CACHE_PREFIX=
|
||||
|
||||
MEMCACHED_HOST=127.0.0.1
|
||||
|
||||
REDIS_CLIENT=phpredis
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.gmail.com
|
||||
MAIL_PORT=465
|
||||
MAIL_USERNAME=pegaslpgsystem@gmail.com
|
||||
MAIL_PASSWORD=
|
||||
MAIL_ENCRYPTION=ssl
|
||||
MAIL_FROM_ADDRESS="pegaslpgsystem@gmail.com"
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||
|
||||
VITE_APP_NAME="${APP_NAME}"
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
* text=auto eol=lf
|
||||
|
||||
*.blade.php diff=html
|
||||
*.css diff=css
|
||||
*.html diff=html
|
||||
*.md diff=markdown
|
||||
*.php diff=php
|
||||
|
||||
/.github export-ignore
|
||||
CHANGELOG.md export-ignore
|
||||
.styleci.yml export-ignore
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
.env.backup
|
||||
.env.production
|
||||
.phpactor.json
|
||||
.phpunit.result.cache
|
||||
/.fleet
|
||||
/.idea
|
||||
/.nova
|
||||
/.phpunit.cache
|
||||
/.vscode
|
||||
/.zed
|
||||
/auth.json
|
||||
/node_modules
|
||||
/public/build
|
||||
/public/hot
|
||||
/public/storage
|
||||
/storage/*.key
|
||||
/storage/pail
|
||||
/vendor
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
Thumbs.db
|
||||
.history/
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
<<<<<<< HEAD
|
||||
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
|
||||
</p>
|
||||
|
||||
## About Laravel
|
||||
|
||||
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
|
||||
|
||||
- [Simple, fast routing engine](https://laravel.com/docs/routing).
|
||||
- [Powerful dependency injection container](https://laravel.com/docs/container).
|
||||
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
|
||||
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
|
||||
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
|
||||
- [Robust background job processing](https://laravel.com/docs/queues).
|
||||
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
|
||||
|
||||
Laravel is accessible, powerful, and provides tools required for large, robust applications.
|
||||
|
||||
## Learning Laravel
|
||||
|
||||
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
|
||||
|
||||
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
|
||||
|
||||
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
|
||||
|
||||
## Laravel Sponsors
|
||||
|
||||
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
|
||||
|
||||
### Premium Partners
|
||||
|
||||
- **[Vehikl](https://vehikl.com)**
|
||||
- **[Tighten Co.](https://tighten.co)**
|
||||
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
|
||||
- **[64 Robots](https://64robots.com)**
|
||||
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
|
||||
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
|
||||
- **[Redberry](https://redberry.international/laravel-development)**
|
||||
- **[Active Logic](https://activelogic.com)**
|
||||
|
||||
## Contributing
|
||||
|
||||
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
|
||||
|
||||
## Security Vulnerabilities
|
||||
|
||||
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
|
||||
|
||||
## License
|
||||
|
||||
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
|
||||
=======
|
||||
# TA-Semester4
|
||||
>>>>>>> ffaee5487316cacdd602ac40f4b044dcb3e5f8b1
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\DataPenjualan;
|
||||
use Maatwebsite\Excel\Concerns\FromQuery;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
|
||||
class DataPenjualanExport implements FromQuery, WithHeadings, WithMapping, ShouldAutoSize
|
||||
{
|
||||
protected $userId;
|
||||
|
||||
public function __construct($userId)
|
||||
{
|
||||
$this->userId = $userId;
|
||||
}
|
||||
|
||||
public function query()
|
||||
{
|
||||
return DataPenjualan::query()
|
||||
->where('user_id', $this->userId)
|
||||
->orderBy('tanggal', 'asc');
|
||||
}
|
||||
|
||||
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
'No',
|
||||
'Tanggal Penjualan',
|
||||
'Jumlah Terjual (Tabung)',
|
||||
];
|
||||
}
|
||||
|
||||
private $rowNumber = 0;
|
||||
public function map($penjualan): array
|
||||
{
|
||||
return [
|
||||
++$this->rowNumber,
|
||||
\Carbon\Carbon::parse($penjualan->tanggal)->translatedFormat('d F Y'),
|
||||
$penjualan->jumlah,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,381 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\DataPenjualan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Carbon\Carbon;
|
||||
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithTitle;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
use Maatwebsite\Excel\Concerns\WithEvents;
|
||||
use Maatwebsite\Excel\Events\AfterSheet;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class DataPenjualanRekapExport implements WithMultipleSheets
|
||||
{
|
||||
/**
|
||||
* Mengatur pembagian sheet (lembar kerja) di dalam file Excel.
|
||||
*/
|
||||
public function sheets(): array
|
||||
{
|
||||
$sheets = [];
|
||||
// Mengambil semua data pengguna dengan peran 'user' (pangkalan)
|
||||
$pangkalanList = User::where(['role' => 'user'])->get();
|
||||
|
||||
// Sheet 1: Membuat halaman ringkasan utama sebagai pusat kontrol evaluasi agen
|
||||
$sheets[] = new RingkasanEvaluasiAgenSheet($pangkalanList);
|
||||
|
||||
// Sheet 2 dan seterusnya: Membuat halaman detail laporan untuk tiap pangkalan
|
||||
foreach ($pangkalanList as $pangkalan) {
|
||||
$sheets[] = new PangkalanSalesSheet($pangkalan);
|
||||
}
|
||||
|
||||
return $sheets;
|
||||
}
|
||||
}
|
||||
|
||||
class RingkasanEvaluasiAgenSheet implements FromCollection, WithTitle, WithHeadings, WithStyles, ShouldAutoSize, WithEvents
|
||||
{
|
||||
private Collection $pangkalanList;
|
||||
|
||||
public function __construct(Collection $pangkalanList)
|
||||
{
|
||||
$this->pangkalanList = $pangkalanList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengatur nama dari sheet pertama.
|
||||
*/
|
||||
public function title(): string
|
||||
{
|
||||
return 'Pusat Pantauan Agen';
|
||||
}
|
||||
|
||||
/**
|
||||
* Memproses data matriks evaluasi seluruh pangkalan untuk ditampilkan di tabel utama.
|
||||
*/
|
||||
public function collection(): Collection
|
||||
{
|
||||
Carbon::setLocale('id');
|
||||
$summaryData = collect();
|
||||
|
||||
foreach ($this->pangkalanList as $index => $pangkalan) {
|
||||
// Cara mengambil data: Total penjualan dihitung per bulan dari data transaksi riil di database
|
||||
$monthlyData = DataPenjualan::where(['user_id' => $pangkalan->id])
|
||||
->select(DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"), DB::raw("SUM(jumlah) as total"))
|
||||
->groupBy('bulan')
|
||||
->get();
|
||||
|
||||
// Jika pangkalan belum memiliki histori transaksi, lewati ke pangkalan berikutnya
|
||||
if ($monthlyData->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$totals = $monthlyData->pluck('total');
|
||||
|
||||
// CARA KELOLA STATISTIK 1: Mencari nilai rata-rata penjualan per bulan
|
||||
$average = $totals->avg();
|
||||
|
||||
// CARA KELOLA STATISTIK 2: Mencari nilai simpangan baku (Standar Deviasi)
|
||||
// Digunakan untuk melihat seberapa jauh jarak naik-turunnya angka penjualan dari nilai rata-rata
|
||||
$variance = 0;
|
||||
foreach ($totals as $t) {
|
||||
$variance += pow(($t - $average), 2);
|
||||
}
|
||||
$stdDev = sqrt($variance / $totals->count());
|
||||
|
||||
// CARA KELOLA STATISTIK 3: Menghitung nilai Koefisien Variasi (CV)
|
||||
// Rumus: Standar Deviasi dibagi Rata-rata. Angka ini menjadi standar ukur kestabilan grafik penjualan.
|
||||
$coefficentOfVariation = $average > 0 ? ($stdDev / $average) : 0;
|
||||
|
||||
// Mengurutkan data untuk mencari bulan dengan volume penjualan tertinggi dan terendah
|
||||
$sortedMonthly = $monthlyData->sortByDesc('total');
|
||||
$highestMonth = Carbon::parse($sortedMonthly->first()->bulan . '-01')->translatedFormat('F Y');
|
||||
$lowestMonth = Carbon::parse($sortedMonthly->last()->bulan . '-01')->translatedFormat('F Y');
|
||||
|
||||
// ATURAN SINKRONISASI REKOMENDASI DAN PENYEBAB:
|
||||
// Jika angka naik-turunnya di atas 30%, maka dianggap tidak stabil dan diberi ulasan evaluasi kuota.
|
||||
if ($coefficentOfVariation > 0.30) {
|
||||
$statusPenting = 'PERLU PERHATIAN KHUSUS';
|
||||
$alasanAnalisis = 'Kesenjangan penjualan antarbulan sangat tinggi. Distribusi kuota wajib disesuaikan secara dinamis.';
|
||||
} else if ($coefficentOfVariation > 0.15) {
|
||||
$statusPenting = 'Pantauan Berkala';
|
||||
$alasanAnalisis = 'Penjualan mengalami fluktuasi tingkat sedang. Diperlukan monitoring per kuartal.';
|
||||
} else {
|
||||
$statusPenting = 'Stabil (Aman)';
|
||||
$alasanAnalisis = 'Pola permintaan pasar konstan. Alokasi kuota tetap dapat dipertahankan.';
|
||||
}
|
||||
|
||||
// Memasukkan hasil olahan ke dalam baris tabel Excel
|
||||
$summaryData->push([
|
||||
$index + 1,
|
||||
$pangkalan->name,
|
||||
(int)round($average) . ' Tabung',
|
||||
$highestMonth,
|
||||
$lowestMonth,
|
||||
round($coefficentOfVariation * 100, 1) . '%', // Mengubah angka desimal menjadi format persen
|
||||
$statusPenting,
|
||||
$alasanAnalisis
|
||||
]);
|
||||
}
|
||||
|
||||
// CARA MENGURUTKAN PRIORITAS:
|
||||
// Pangkalan dengan status 'PERLU PERHATIAN KHUSUS' dipaksa otomatis naik ke urutan baris paling atas
|
||||
return $summaryData->sortBy(function($row) {
|
||||
return $row[6] === 'PERLU PERHATIAN KHUSUS' ? 0 : 1;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengatur baris judul (Header) tabel di sheet pertama.
|
||||
*/
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
['DASHBOARD UTAMA MONITORING AGEN: MATRIKS EVALUASI DISTRIBUSI'],
|
||||
['Diunduh tgl:', Carbon::now()->translatedFormat('d F Y H:i') . ' WIB'],
|
||||
['Berikut adalah daftar pangkalan yang diurutkan berdasarkan prioritas pengawasan volume jual.'],
|
||||
[''],
|
||||
['No', 'Nama Pangkalan', 'Rata-rata / Bulan', 'Bulan Tertinggi', 'Bulan Terendah', 'Tingkat Fluktuasi (CV)', 'Rekomendasi Tindakan', 'Penyebab / Alasan Analisis']
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengatur desain pewarnaan teks dan latar belakang header tabel.
|
||||
*/
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
return [
|
||||
1 => ['font' => ['bold' => true, 'size' => 14, 'color' => ['rgb' => '111111']]],
|
||||
2 => ['font' => ['italic' => true, 'size' => 10]],
|
||||
5 => [
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '1F4E79']]
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengatur tata letak dan pewarnaan otomatis (Conditional Formatting) sel setelah sheet selesai dibuat.
|
||||
*/
|
||||
public function registerEvents(): array
|
||||
{
|
||||
return [
|
||||
AfterSheet::class => function (AfterSheet $event) {
|
||||
$sheet = $event->sheet->getDelegate();
|
||||
$highestRow = $sheet->getHighestRow();
|
||||
|
||||
// Menggabungkan kolom untuk area baris judul atas
|
||||
$sheet->mergeCells("A1:H1");
|
||||
$sheet->mergeCells("A2:H2");
|
||||
$sheet->mergeCells("A3:H3");
|
||||
|
||||
// Memberikan garis pembatas (Border) tipis abu-abu ke seluruh sel tabel
|
||||
$styleArray = [
|
||||
'borders' => [
|
||||
'allBorders' => [
|
||||
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
|
||||
'color' => ['rgb' => 'CCCCCC'],
|
||||
],
|
||||
],
|
||||
];
|
||||
$sheet->getStyle("A5:H{$highestRow}")->applyFromArray($styleArray);
|
||||
|
||||
// ATURAN WARNA OTOMATIS:
|
||||
// Membaca isi kolom G, jika status kritis maka otomatis diwarnai merah muda cerah.
|
||||
for ($row = 6; $row <= $highestRow; $row++) {
|
||||
$cellValue = $sheet->getCell("G{$row}")->getValue();
|
||||
if (str_contains($cellValue, 'PERHATIAN KHUSUS')) {
|
||||
$sheet->getStyle("G{$row}")->getFont()->setBold(true)->getColor()->setRGB('9C0006');
|
||||
$sheet->getStyle("G{$row}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('FFC7CE');
|
||||
} elseif (str_contains($cellValue, 'Pantauan Berkala')) {
|
||||
$sheet->getStyle("G{$row}")->getFont()->setBold(true)->getColor()->setRGB('9C6500');
|
||||
$sheet->getStyle("G{$row}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('FFEB9C');
|
||||
} else {
|
||||
$sheet->getStyle("G{$row}")->getFont()->getColor()->setRGB('006100');
|
||||
$sheet->getStyle("G{$row}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('C6EFCE');
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class PangkalanSalesSheet implements FromCollection, WithTitle, WithHeadings, WithStyles, ShouldAutoSize, WithEvents
|
||||
{
|
||||
private User $pangkalan;
|
||||
private string $highestMonth = '-';
|
||||
private string $lowestMonth = '-';
|
||||
private Collection $monthlySummary;
|
||||
|
||||
public function __construct(User $pangkalan)
|
||||
{
|
||||
$this->pangkalan = $pangkalan;
|
||||
$this->monthlySummary = collect();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengatur nama sheet pangkalan (dibersihkan dari karakter spesial agar tidak error).
|
||||
*/
|
||||
public function title(): string
|
||||
{
|
||||
return substr(preg_replace('/[^A-Za-z0-9 ]/', '', $this->pangkalan->name), 0, 30);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengambil data transaksi harian riil pangkalan untuk dicetak ke dalam sheet detail.
|
||||
*/
|
||||
public function collection(): Collection
|
||||
{
|
||||
Carbon::setLocale('id');
|
||||
|
||||
// Mengambil data urut dari tanggal terlama ke terbaru dan membuang data duplikat tanggal
|
||||
$data = DataPenjualan::where(['user_id' => $this->pangkalan->id])
|
||||
->select('tanggal', 'jumlah')
|
||||
->orderBy('tanggal', 'asc')
|
||||
->get()
|
||||
->unique('tanggal');
|
||||
|
||||
// Mengambil data rekap bulanan untuk bahan tabel ringkasan di bagian bawah
|
||||
$analytics = DataPenjualan::where(['user_id' => $this->pangkalan->id])
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan_tahun"),
|
||||
DB::raw("SUM(jumlah) as total")
|
||||
)
|
||||
->groupBy('bulan_tahun')
|
||||
->orderBy('total', 'desc')
|
||||
->get();
|
||||
|
||||
if ($analytics->isNotEmpty()) {
|
||||
$this->highestMonth = Carbon::parse($analytics->first()->bulan_tahun . '-01')->translatedFormat('F Y');
|
||||
$this->lowestMonth = Carbon::parse($analytics->last()->bulan_tahun . '-01')->translatedFormat('F Y');
|
||||
|
||||
$this->monthlySummary = $analytics->map(function ($item) {
|
||||
return [
|
||||
'bulan' => Carbon::parse($item->bulan_tahun . '-01')->translatedFormat('F Y'),
|
||||
'total' => (int)$item->total
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
// Aturan proteksi: Jika data kosong, otomatis cetak angka 0 agar tidak kosong/NaN
|
||||
if ($data->isEmpty()) {
|
||||
return collect([[Carbon::today()->format('Y-m-d'), 0]]);
|
||||
}
|
||||
|
||||
return $data->map(function ($item) {
|
||||
return [
|
||||
Carbon::parse($item->tanggal)->translatedFormat('d F Y'),
|
||||
$item->jumlah !== null && $item->jumlah !== '' ? (int)$item->jumlah : 0 // Proteksi angka 0 mutlak
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengatur bagian informasi tata letak atas berkas rekapitulasi pangkalan.
|
||||
*/
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
['LAPORAN REKAPITULASI PENJUALAN LPG OLEH AGEN'],
|
||||
['Nama Pangkalan:', $this->pangkalan->name],
|
||||
['Alamat Lokasi:', $this->pangkalan->alamat ?? 'Jember'],
|
||||
[""],
|
||||
['Tanggal Transaksi', 'Volume Penjualan (Tabung)']
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Desain pewarnaan tabel transaksi harian pangkalan (Hijau).
|
||||
*/
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
return [
|
||||
1 => ['font' => ['bold' => true, 'size' => 14, 'color' => ['rgb' => '111111']]],
|
||||
2 => ['font' => ['bold' => true]],
|
||||
3 => ['font' => ['bold' => true]],
|
||||
5 => [
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '7BB31A']]
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Menyusun tabel ringkasan bulanan dan kotak ulasan Agen di bagian bawah setelah data harian dicetak.
|
||||
*/
|
||||
public function registerEvents(): array
|
||||
{
|
||||
return [
|
||||
AfterSheet::class => function (AfterSheet $event) {
|
||||
$sheet = $event->sheet->getDelegate();
|
||||
$highestRow = $sheet->getHighestRow();
|
||||
|
||||
$sheet->mergeCells("A1:B1");
|
||||
|
||||
$styleArray = [
|
||||
'borders' => [
|
||||
'allBorders' => [
|
||||
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
|
||||
'color' => ['rgb' => 'CCCCCC'],
|
||||
],
|
||||
],
|
||||
];
|
||||
$sheet->getStyle("A5:B{$highestRow}")->applyFromArray($styleArray);
|
||||
$sheet->getStyle("B6:B{$highestRow}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
|
||||
|
||||
// 1. MEMBUAT TABEL REKAP BULANAN (Warna Biru)
|
||||
$summaryStartRow = $highestRow + 3;
|
||||
$sheet->mergeCells("A{$summaryStartRow}:B{$summaryStartRow}");
|
||||
$sheet->setCellValue("A{$summaryStartRow}", " RINGKASAN TOTAL PENJUALAN PER BULAN (TERTINGGI KE TERENDAH)");
|
||||
$sheet->getStyle("A{$summaryStartRow}")->getFont()->setBold(true)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE));
|
||||
$sheet->getStyle("A{$summaryStartRow}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('4E73DF');
|
||||
|
||||
$headerRow = $summaryStartRow + 1;
|
||||
$sheet->setCellValue("A{$headerRow}", "Bulan & Tahun");
|
||||
$sheet->setCellValue("B{$headerRow}", "Total Terjual (Tabung)");
|
||||
$sheet->getStyle("A{$headerRow}:B{$headerRow}")->getFont()->setBold(true);
|
||||
$sheet->getStyle("A{$headerRow}:B{$headerRow}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EAECF4');
|
||||
|
||||
// Menuliskan isi rekap bulanan yang sudah berurutan dari tertinggi
|
||||
$currentRow = $headerRow + 1;
|
||||
foreach ($this->monthlySummary as $sum) {
|
||||
$sheet->setCellValue("A{$currentRow}", $sum['bulan']);
|
||||
$sheet->setCellValue("B{$currentRow}", $sum['total']);
|
||||
$sheet->getStyle("B{$currentRow}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
|
||||
$currentRow++;
|
||||
}
|
||||
$sheet->getStyle("A{$headerRow}:B" . ($currentRow - 1))->applyFromArray($styleArray);
|
||||
|
||||
// 2. MEMBUAT KOTAK KESIMPULAN MONITORING (Warna Merah)
|
||||
$analysisStartRow = $currentRow + 2;
|
||||
$sheet->mergeCells("A{$analysisStartRow}:B{$analysisStartRow}");
|
||||
$sheet->setCellValue("A{$analysisStartRow}", " KESIMPULAN ANALISIS & MONITORING AGEN");
|
||||
$sheet->getStyle("A{$analysisStartRow}")->getFont()->setBold(true)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE));
|
||||
$sheet->getStyle("A{$analysisStartRow}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('E74A3B');
|
||||
|
||||
$r1 = $analysisStartRow + 1;
|
||||
$sheet->mergeCells("A{$r1}:B{$r1}");
|
||||
$sheet->setCellValue("A{$r1}", " • Penjualan volume tertinggi pangkalan ini tercatat pada periode: " . $this->highestMonth);
|
||||
|
||||
$r2 = $analysisStartRow + 2;
|
||||
$sheet->mergeCells("A{$r2}:B{$r2}");
|
||||
$sheet->setCellValue("A{$r2}", " • Penjualan volume terendah pangkalan ini tercatat pada periode: " . $this->lowestMonth);
|
||||
|
||||
$r3 = $analysisStartRow + 3;
|
||||
$sheet->mergeCells("A{$r3}:B{$r3}");
|
||||
$sheet->setCellValue("A{$r3}", " • CATATAN AGEN: Jadikan bulan-bulan dengan volume terendah sebagai acuan untuk menyesuaikan kuota distribusi secara efisien, guna menghindari penumpukan stok berlebih di pangkalan.");
|
||||
|
||||
// Membuat garis bingkai tebal warna merah mengelilingi teks kesimpulan
|
||||
$boxRange = "A{$analysisStartRow}:B" . ($analysisStartRow + 4);
|
||||
$sheet->getStyle($boxRange)->getBorders()->getOutline()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM)->getColor()->setRGB('E74A3B');
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\HasilPrediksi;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
|
||||
class HasilPrediksiExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
|
||||
{
|
||||
protected $id;
|
||||
private $rowNumber = 0;
|
||||
|
||||
public function __construct($id) {
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
public function collection() {
|
||||
return HasilPrediksi::where('user_id', $this->id)
|
||||
->orderBy('tanggal', 'asc')
|
||||
->get();
|
||||
}
|
||||
|
||||
public function headings(): array {
|
||||
return ["No", "Tanggal", "Estimasi (Tabung)", "Batas Bawah", "Batas Atas"];
|
||||
}
|
||||
|
||||
public function map($row): array {
|
||||
$this->rowNumber++;
|
||||
return [
|
||||
$this->rowNumber,
|
||||
\Carbon\Carbon::parse($row->tanggal)->translatedFormat('d F Y'),
|
||||
(int)($row->estimasi ?? 0),
|
||||
(int)($row->batas_bawah ?? 0),
|
||||
(int)($row->batas_atas ?? 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,350 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\HasilPrediksi;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Carbon\Carbon;
|
||||
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithTitle;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
use Maatwebsite\Excel\Concerns\WithEvents;
|
||||
use Maatwebsite\Excel\Events\AfterSheet;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class HasilPrediksiRekapExport implements WithMultipleSheets
|
||||
{
|
||||
public function sheets(): array
|
||||
{
|
||||
$sheets = [];
|
||||
$pangkalanList = User::where(['role' => 'user'])->get();
|
||||
|
||||
// Sheet 1: Halaman monitoring dashboard utama untuk semua pangkalan
|
||||
$sheets[] = new RingkasanEvaluasiPrediksiSheet($pangkalanList);
|
||||
|
||||
// Sheet 2 dan seterusnya: Laporan detail per pangkalan
|
||||
foreach ($pangkalanList as $pangkalan) {
|
||||
$sheets[] = new PangkalanPredictionSheet($pangkalan);
|
||||
}
|
||||
|
||||
return $sheets;
|
||||
}
|
||||
}
|
||||
|
||||
class RingkasanEvaluasiPrediksiSheet implements FromCollection, WithTitle, WithHeadings, WithStyles, ShouldAutoSize, WithEvents
|
||||
{
|
||||
private Collection $pangkalanList;
|
||||
|
||||
public function __construct(Collection $pangkalanList)
|
||||
{
|
||||
$this->pangkalanList = $pangkalanList;
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return 'Pusat Mitigasi Prediksi';
|
||||
}
|
||||
|
||||
public function collection(): Collection
|
||||
{
|
||||
Carbon::setLocale('id');
|
||||
$summaryData = collect();
|
||||
|
||||
foreach ($this->pangkalanList as $index => $pangkalan) {
|
||||
// Mengambil total estimasi, total batas bawah, dan total batas atas per bulan
|
||||
$monthlyData = HasilPrediksi::where(['user_id' => $pangkalan->id])
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"),
|
||||
DB::raw("SUM(estimasi) as total_estimasi"),
|
||||
DB::raw("SUM(batas_bawah) as total_bawah"),
|
||||
DB::raw("SUM(batas_atas) as total_atas")
|
||||
)
|
||||
->groupBy('bulan')
|
||||
->get();
|
||||
|
||||
if ($monthlyData->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mencari bulan dengan nilai estimasi tertinggi
|
||||
$sortedMonthly = $monthlyData->sortByDesc('total_estimasi');
|
||||
$highestPredRow = $sortedMonthly->first();
|
||||
$lowestPredRow = $sortedMonthly->last();
|
||||
|
||||
$highestMonth = Carbon::parse($highestPredRow->bulan . '-01')->translatedFormat('F Y');
|
||||
$lowestMonth = Carbon::parse($lowestPredRow->bulan . '-01')->translatedFormat('F Y');
|
||||
|
||||
$peakValue = (int)$highestPredRow->total_estimasi;
|
||||
$averageValue = (int)round($monthlyData->pluck('total_estimasi')->avg());
|
||||
$averageBawah = (int)round($monthlyData->pluck('total_bawah')->avg());
|
||||
$averageAtas = (int)round($monthlyData->pluck('total_atas')->avg());
|
||||
|
||||
// Menghitung persentase kenaikan puncak terhadap rata-rata bulanan
|
||||
$persentaseKenaikan = $averageValue > 0 ? (($peakValue - $averageValue) / $averageValue) * 100 : 0;
|
||||
|
||||
if ($persentaseKenaikan > 20.0) {
|
||||
$statusTindakan = 'PERLU PERHATIAN KHUSUS';
|
||||
$alasanAnalisis = 'Diproyeksikan mengalami lonjakan permintaan ekstrem sebesar ' . round($persentaseKenaikan, 1) . '%. Alokasi pasokan wajib ditambah mendekati batas atas.';
|
||||
} else if ($persentaseKenaikan > 10.0) {
|
||||
$statusTindakan = 'Pantauan Berkala';
|
||||
$alasanAnalisis = 'Terdapat indikasi kenaikan permintaan pasar tingkat sedang. Diperlukan pemantauan stok berkala.';
|
||||
} else {
|
||||
$statusTindakan = 'Stabil (Aman)';
|
||||
$alasanAnalisis = 'Proyeksi fluktuasi permintaan cenderung landai. Alokasi kuota reguler aman.';
|
||||
}
|
||||
|
||||
$summaryData->push([
|
||||
$index + 1,
|
||||
$pangkalan->name,
|
||||
$averageValue . ' Tabung',
|
||||
$averageBawah . ' Tabung', // Tambahan Kolom Rata-rata Batas Bawah bulanan
|
||||
$averageAtas . ' Tabung', // Tambahan Kolom Rata-rata Batas Atas bulanan
|
||||
$highestMonth,
|
||||
$peakValue . ' Tabung',
|
||||
round($persentaseKenaikan, 1) . '%',
|
||||
$statusTindakan,
|
||||
$alasanAnalisis
|
||||
]);
|
||||
}
|
||||
|
||||
// Urutkan berdasarkan pangkalan yang statusnya PERLU PERHATIAN KHUSUS paling atas
|
||||
return $summaryData->sortBy(function($row) {
|
||||
return $row[8] === 'PERLU PERHATIAN KHUSUS' ? 0 : 1;
|
||||
});
|
||||
}
|
||||
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
['DASHBOARD UTAMA MONITORING PREDIKSI AGEN: MITIGASI KERAWANAN PASOKAN'],
|
||||
['Diunduh tgl:', Carbon::now()->translatedFormat('d F Y H:i') . ' WIB'],
|
||||
['Berikut adalah daftar pangkalan yang diurutkan berdasarkan skala prioritas penambahan stok akibat proyeksi lonjakan tertinggi.'],
|
||||
[''],
|
||||
['No', 'Nama Pangkalan', 'Rata-rata Prediksi / Bulan', 'Rata-rata Batas Bawah', 'Rata-rata Batas Atas', 'Bulan Lonjakan Tertinggi', 'Estimasi Puncak (Tabung)', 'Persentase Kenaikan', 'Rekomendasi Tindakan Agen', 'Penyebab / Alasan Analisis']
|
||||
];
|
||||
}
|
||||
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
return [
|
||||
1 => ['font' => ['bold' => true, 'size' => 14, 'color' => ['rgb' => '111111']]],
|
||||
2 => ['font' => ['italic' => true, 'size' => 10]],
|
||||
5 => [
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '1F4E79']]
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public function registerEvents(): array
|
||||
{
|
||||
return [
|
||||
AfterSheet::class => function (AfterSheet $event) {
|
||||
$sheet = $event->sheet->getDelegate();
|
||||
$highestRow = $sheet->getHighestRow();
|
||||
|
||||
$sheet->mergeCells("A1:J1");
|
||||
$sheet->mergeCells("A2:J2");
|
||||
$sheet->mergeCells("A3:J3");
|
||||
|
||||
$styleArray = [
|
||||
'borders' => [
|
||||
'allBorders' => [
|
||||
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
|
||||
'color' => ['rgb' => 'CCCCCC'],
|
||||
],
|
||||
],
|
||||
];
|
||||
$sheet->getStyle("A5:J{$highestRow}")->applyFromArray($styleArray);
|
||||
|
||||
for ($row = 6; $row <= $highestRow; $row++) {
|
||||
$cellValue = $sheet->getCell("I{$row}")->getValue();
|
||||
if (str_contains($cellValue, 'PERHATIAN KHUSUS')) {
|
||||
$sheet->getStyle("I{$row}")->getFont()->setBold(true)->getColor()->setRGB('9C0006');
|
||||
$sheet->getStyle("I{$row}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('FFC7CE');
|
||||
} elseif (str_contains($cellValue, 'Pantauan Berkala')) {
|
||||
$sheet->getStyle("I{$row}")->getFont()->setBold(true)->getColor()->setRGB('9C6500');
|
||||
$sheet->getStyle("I{$row}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('FFEB9C');
|
||||
} else {
|
||||
$sheet->getStyle("I{$row}")->getFont()->getColor()->setRGB('006100');
|
||||
$sheet->getStyle("I{$row}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('C6EFCE');
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class PangkalanPredictionSheet implements FromCollection, WithTitle, WithHeadings, WithStyles, ShouldAutoSize, WithEvents
|
||||
{
|
||||
private User $pangkalan;
|
||||
private string $highestMonth = '-';
|
||||
private string $lowestMonth = '-';
|
||||
private int $highestBatasAtas = 0;
|
||||
private int $lowestBatasBawah = 0;
|
||||
private Collection $monthlySummary;
|
||||
|
||||
public function __construct(User $pangkalan)
|
||||
{
|
||||
$this->pangkalan = $pangkalan;
|
||||
$this->monthlySummary = collect();
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return substr(preg_replace('/[^A-Za-z0-9 ]/', '', $this->pangkalan->name), 0, 30);
|
||||
}
|
||||
|
||||
public function collection(): Collection
|
||||
{
|
||||
Carbon::setLocale('id');
|
||||
|
||||
// Mengambil riwayat detail harian prediksi (Termasuk kolom batas bawah dan batas atas)
|
||||
$data = HasilPrediksi::where(['user_id' => $this->pangkalan->id])
|
||||
->select('tanggal', 'estimasi', 'batas_bawah', 'batas_atas')
|
||||
->orderBy('tanggal', 'asc')
|
||||
->get()
|
||||
->unique('tanggal');
|
||||
|
||||
// Merekap nilai bulanan estimasi, batas bawah, dan batas atas
|
||||
$analytics = HasilPrediksi::where(['user_id' => $this->pangkalan->id])
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan_tahun"),
|
||||
DB::raw("SUM(estimasi) as total"),
|
||||
DB::raw("SUM(batas_bawah) as total_bawah"),
|
||||
DB::raw("SUM(batas_atas) as total_atas")
|
||||
)
|
||||
->groupBy('bulan_tahun')
|
||||
->orderBy('total', 'desc')
|
||||
->get();
|
||||
|
||||
if ($analytics->isNotEmpty()) {
|
||||
$this->highestMonth = Carbon::parse($analytics->first()->bulan_tahun . '-01')->translatedFormat('F Y');
|
||||
$this->lowestMonth = Carbon::parse($analytics->last()->bulan_tahun . '-01')->translatedFormat('F Y');
|
||||
$this->highestBatasAtas = (int)$analytics->first()->total_atas;
|
||||
$this->lowestBatasBawah = (int)$analytics->last()->total_bawah;
|
||||
|
||||
$this->monthlySummary = $analytics->map(function ($item) {
|
||||
return [
|
||||
'bulan' => Carbon::parse($item->bulan_tahun . '-01')->translatedFormat('F Y'),
|
||||
'total' => (int)$item->total,
|
||||
'bawah' => (int)$item->total_bawah,
|
||||
'atas' => (int)$item->total_atas
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
if ($data->isEmpty()) {
|
||||
return collect([[Carbon::today()->format('Y-m-d'), 0, 0, 0]]);
|
||||
}
|
||||
|
||||
return $data->map(function ($item) {
|
||||
return [
|
||||
Carbon::parse($item->tanggal)->translatedFormat('d F Y'),
|
||||
$item->estimasi !== null && $item->estimasi !== '' ? (int)$item->estimasi : 0,
|
||||
$item->batas_bawah !== null && $item->batas_bawah !== '' ? (int)$item->batas_bawah : 0,
|
||||
$item->batas_atas !== null && $item->batas_atas !== '' ? (int)$item->batas_atas : 0,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
['LAPORAN PROYEKSI ESTIMASI HASIL PREDIKSI KEBUTUHAN LPG'],
|
||||
['Nama Pangkalan:', $this->pangkalan->name],
|
||||
['Alamat Lokasi:', $this->pangkalan->alamat ?? 'Jember'],
|
||||
[""],
|
||||
['Tanggal Prediksi', 'Estimasi Kebutuhan (Tabung)', 'Batas Bawah', 'Batas Atas']
|
||||
];
|
||||
}
|
||||
|
||||
public function styles(Worksheet $sheet): array
|
||||
{
|
||||
return [
|
||||
1 => ['font' => ['bold' => true, 'size' => 14, 'color' => ['rgb' => '111111']]],
|
||||
2 => ['font' => ['bold' => true]],
|
||||
3 => ['font' => ['bold' => true]],
|
||||
5 => [
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '36B9CC']]
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public function registerEvents(): array
|
||||
{
|
||||
return [
|
||||
AfterSheet::class => function (AfterSheet $event) {
|
||||
$sheet = $event->sheet->getDelegate();
|
||||
$highestRow = $sheet->getHighestRow();
|
||||
|
||||
$sheet->mergeCells("A1:D1");
|
||||
|
||||
$styleArray = [
|
||||
'borders' => [
|
||||
'allBorders' => [
|
||||
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
|
||||
'color' => ['rgb' => 'CCCCCC'],
|
||||
],
|
||||
],
|
||||
];
|
||||
$sheet->getStyle("A5:D{$highestRow}")->applyFromArray($styleArray);
|
||||
$sheet->getStyle("B6:D{$highestRow}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
|
||||
|
||||
// 1. MEMBUAT TABEL REKAP BULANAN PREDIKSI + REKAP BATAS BAWAH ATAS
|
||||
$summaryStartRow = $highestRow + 3;
|
||||
$sheet->mergeCells("A{$summaryStartRow}:D{$summaryStartRow}");
|
||||
$sheet->setCellValue("A{$summaryStartRow}", " RINGKASAN TOTAL ESTIMASI PREDIKSI PER BULAN (TERTINGGI KE TERENDAH)");
|
||||
$sheet->getStyle("A{$summaryStartRow}")->getFont()->setBold(true)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE));
|
||||
$sheet->getStyle("A{$summaryStartRow}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('1F4E79');
|
||||
|
||||
$headerRow = $summaryStartRow + 1;
|
||||
$sheet->setCellValue("A{$headerRow}", "Bulan & Tahun");
|
||||
$sheet->setCellValue("B{$headerRow}", "Total Estimasi (Tabung)");
|
||||
$sheet->setCellValue("C{$headerRow}", "Rekap Batas Bawah");
|
||||
$sheet->setCellValue("D{$headerRow}", "Rekap Batas Atas");
|
||||
$sheet->getStyle("A{$headerRow}:D{$headerRow}")->getFont()->setBold(true);
|
||||
$sheet->getStyle("A{$headerRow}:D{$headerRow}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('EAECF4');
|
||||
|
||||
$currentRow = $headerRow + 1;
|
||||
foreach ($this->monthlySummary as $sum) {
|
||||
$sheet->setCellValue("A{$currentRow}", $sum['bulan']);
|
||||
$sheet->setCellValue("B{$currentRow}", $sum['total']);
|
||||
$sheet->setCellValue("C{$currentRow}", $sum['bawah']);
|
||||
$sheet->setCellValue("D{$currentRow}", $sum['atas']);
|
||||
$sheet->getStyle("B{$currentRow}:D{$currentRow}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
|
||||
$currentRow++;
|
||||
}
|
||||
$sheet->getStyle("A{$headerRow}:D" . ($currentRow - 1))->applyFromArray($styleArray);
|
||||
|
||||
// 2. KOTAK MONITORING KESIMPULAN
|
||||
$analysisStartRow = $currentRow + 2;
|
||||
$sheet->mergeCells("A{$analysisStartRow}:D{$analysisStartRow}");
|
||||
$sheet->setCellValue("A{$analysisStartRow}", " KESIMPULAN ANALISIS & MONITORING PROYEKSI PASOKAN");
|
||||
$sheet->getStyle("A{$analysisStartRow}")->getFont()->setBold(true)->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE));
|
||||
$sheet->getStyle("A{$analysisStartRow}")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('D94F04');
|
||||
|
||||
$r1 = $analysisStartRow + 1;
|
||||
$sheet->mergeCells("A{$r1}:D{$r1}");
|
||||
$sheet->setCellValue("A{$r1}", " • Proyeksi lonjakan tertinggi diprediksi pada bulan " . $this->highestMonth . " dengan potensi puncak pasokan atas mencapai: " . $this->highestBatasAtas . " Tabung.");
|
||||
|
||||
$r2 = $analysisStartRow + 2;
|
||||
$sheet->mergeCells("A{$r2}:D{$r2}");
|
||||
$sheet->setCellValue("A{$r2}", " • Proyeksi permintaan terendah diprediksi pada bulan " . $this->lowestMonth . " dengan batas bawah pasokan minimum sebesar: " . $this->lowestBatasBawah . " Tabung.");
|
||||
|
||||
$r3 = $analysisStartRow + 3;
|
||||
$sheet->mergeCells("A{$r3}:D{$r3}");
|
||||
$sheet->setCellValue("A{$r3}", " • CATATAN AGEN: Jadikan bulan-bulan dengan volume tertinggi sebagai acuan utama penambahan pasokan taktis secara efisien, guna menghindari risiko kelangkaan stok LPG di pangkalan.");
|
||||
|
||||
$boxRange = "A{$analysisStartRow}:D" . ($analysisStartRow + 4);
|
||||
$sheet->getStyle($boxRange)->getBorders()->getOutline()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM)->getColor()->setRGB('D94F04');
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\HasilPrediksi;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class PrediksiExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
|
||||
{
|
||||
protected $year;
|
||||
protected $month;
|
||||
private $rowNumber = 0;
|
||||
|
||||
public function __construct($year, $month) {
|
||||
$this->year = $year;
|
||||
$this->month = $month;
|
||||
}
|
||||
|
||||
public function collection() {
|
||||
return HasilPrediksi::where('user_id', Auth::id())
|
||||
->whereRaw('YEAR(tanggal) = ?', [$this->year])
|
||||
->whereRaw('MONTH(tanggal) = ?', [$this->month])
|
||||
->orderBy('tanggal', 'asc')
|
||||
->get();
|
||||
}
|
||||
|
||||
public function headings(): array {
|
||||
return ["No", "Tanggal", "Estimasi (Tabung)", "Batas Bawah", "Batas Atas"];
|
||||
}
|
||||
|
||||
public function map($row): array {
|
||||
$this->rowNumber++;
|
||||
return [
|
||||
$this->rowNumber,
|
||||
\Carbon\Carbon::parse($row->tanggal)->translatedFormat('d F Y'),
|
||||
(int)($row->estimasi ?? 0),
|
||||
(int)($row->batas_bawah ?? 0),
|
||||
(int)($row->batas_atas ?? 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\Helpdesk;
|
||||
use App\Models\Artikel;
|
||||
use App\Models\Faq;
|
||||
use App\Models\HasilPrediksi;
|
||||
use App\Models\DataPenjualan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class DashboardAdminControllers extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
// Mengubah ke format Array untuk membuang spasi gaib penyebab error 'role' dan 'status'
|
||||
$totalUser = User::where(['role' => 'user'])->count();
|
||||
$pendingBantuan = Helpdesk::where(['status' => 'pending'])->count();
|
||||
$totalArtikel = Artikel::count();
|
||||
$totalFaq = Faq::count();
|
||||
|
||||
$rerataPenjualan = (int) round(DataPenjualan::avg('jumlah') ?? 0);
|
||||
|
||||
$selectedPangkalanId = $request->filled('pangkalan_id') ? (string) $request->input('pangkalan_id') : null;
|
||||
|
||||
if ($selectedPangkalanId !== null) {
|
||||
$lastTransaction = DataPenjualan::where(['user_id' => $selectedPangkalanId])->orderBy('tanggal', 'desc')->first();
|
||||
} else {
|
||||
$lastTransaction = DataPenjualan::orderBy('tanggal', 'desc')->first();
|
||||
}
|
||||
|
||||
$baseDate = $lastTransaction ? Carbon::parse($lastTransaction->tanggal) : Carbon::today();
|
||||
|
||||
/** @var Collection $pangkalanList */
|
||||
$pangkalanList = User::where(['role' => 'user'])->get();
|
||||
|
||||
$salesChart = $this->generateSalesChartData($baseDate, $selectedPangkalanId);
|
||||
$chartDates = $salesChart['dates'];
|
||||
$chartLabels = $salesChart['labels'];
|
||||
$lineChartData = $salesChart['data'];
|
||||
$totalDataAsliTersedia = $salesChart['total'];
|
||||
|
||||
$predictionChart = $this->generatePredictionChartData($baseDate, $selectedPangkalanId);
|
||||
$predictionDates = $predictionChart['dates'];
|
||||
$predictionLabels = $predictionChart['labels'];
|
||||
$predictionChartData = $predictionChart['data'];
|
||||
$totalPrediksiTersedia = $predictionChart['total'];
|
||||
|
||||
$pieData = $this->generatePieData();
|
||||
$aktivitasPrediksi = $this->generateAktivitasLogData($pangkalanList);
|
||||
$recentBantuan = Helpdesk::with('user')->latest()->take(5)->get();
|
||||
|
||||
return view('admin.dashboard.index', compact(
|
||||
'totalUser', 'pendingBantuan', 'totalArtikel', 'totalFaq', 'pangkalanList', 'selectedPangkalanId',
|
||||
'rerataPenjualan', 'lineChartData', 'chartDates', 'chartLabels', 'totalDataAsliTersedia',
|
||||
'pieData', 'aktivitasPrediksi', 'predictionChartData', 'predictionDates', 'predictionLabels', 'totalPrediksiTersedia', 'recentBantuan'
|
||||
));
|
||||
}
|
||||
|
||||
private function generateSalesChartData(Carbon $baseDate, ?string $selectedPangkalanId): array
|
||||
{
|
||||
$chartDates = collect();
|
||||
for ($i = 6; $i >= 0; $i--) {
|
||||
$chartDates->push((clone $baseDate)->subDays($i)->format('Y-m-d'));
|
||||
}
|
||||
|
||||
$chartLabels = $chartDates->map(function($d) {
|
||||
return Carbon::parse($d)->locale('id')->translatedFormat('d M');
|
||||
})->toArray();
|
||||
|
||||
$lineChartData = [];
|
||||
$totalDataAsliTersedia = 0;
|
||||
|
||||
if ($selectedPangkalanId !== null) {
|
||||
$pangkalan = User::where(['role' => 'user'])->find($selectedPangkalanId);
|
||||
if ($pangkalan) {
|
||||
$pangkalanData = [];
|
||||
foreach ($chartDates as $date) {
|
||||
// Menggunakan struktur array pasangkan data kolom secara presisi
|
||||
$nilaiJual = (int) DataPenjualan::where(['user_id' => $pangkalan->id, 'tanggal' => $date])->sum('jumlah');
|
||||
$pangkalanData[] = $nilaiJual;
|
||||
$totalDataAsliTersedia += $nilaiJual;
|
||||
}
|
||||
$lineChartData[] = [
|
||||
'label' => $pangkalan->name,
|
||||
'data' => $pangkalanData
|
||||
];
|
||||
}
|
||||
} else {
|
||||
$globalSalesData = [];
|
||||
foreach ($chartDates as $date) {
|
||||
$nilaiJualGlobal = (int) DataPenjualan::where(['tanggal' => $date])->sum('jumlah');
|
||||
$globalSalesData[] = $nilaiJualGlobal;
|
||||
$totalDataAsliTersedia += $nilaiJualGlobal;
|
||||
}
|
||||
$lineChartData[] = [
|
||||
'label' => 'Total Volume Seluruh Pangkalan',
|
||||
'data' => $globalSalesData
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'dates' => $chartDates,
|
||||
'labels' => $chartLabels,
|
||||
'data' => $lineChartData,
|
||||
'total' => $totalDataAsliTersedia
|
||||
];
|
||||
}
|
||||
|
||||
private function generatePredictionChartData(Carbon $baseDate, ?string $selectedPangkalanId): array
|
||||
{
|
||||
$predictionDates = collect();
|
||||
for ($i = 1; $i <= 7; $i++) {
|
||||
$predictionDates->push((clone $baseDate)->addDays($i)->format('Y-m-d'));
|
||||
}
|
||||
|
||||
$predictionLabels = $predictionDates->map(function($d) {
|
||||
return Carbon::parse($d)->locale('id')->translatedFormat('d M');
|
||||
})->toArray();
|
||||
|
||||
$predictionChartData = [];
|
||||
$totalPrediksiTersedia = 0;
|
||||
|
||||
if ($selectedPangkalanId !== null) {
|
||||
$pangkalan = User::where(['role' => 'user'])->find($selectedPangkalanId);
|
||||
if ($pangkalan) {
|
||||
$pangkalanPrediksi = [];
|
||||
foreach ($predictionDates as $date) {
|
||||
$nilaiEstimasi = (int) HasilPrediksi::where(['user_id' => $pangkalan->id, 'tanggal' => $date])->sum('estimasi');
|
||||
$pangkalanPrediksi[] = $nilaiEstimasi;
|
||||
$totalPrediksiTersedia += $nilaiEstimasi;
|
||||
}
|
||||
$predictionChartData[] = [
|
||||
'label' => $pangkalan->name,
|
||||
'data' => $pangkalanPrediksi
|
||||
];
|
||||
}
|
||||
} else {
|
||||
$globalPredData = [];
|
||||
foreach ($predictionDates as $date) {
|
||||
$nilaiEstimasiGlobal = (int) HasilPrediksi::where(['tanggal' => $date])->sum('estimasi');
|
||||
$globalPredData[] = $nilaiEstimasiGlobal;
|
||||
$totalPrediksiTersedia += $nilaiEstimasiGlobal;
|
||||
}
|
||||
$predictionChartData[] = [
|
||||
'label' => 'Total Estimasi Seluruh Pangkalan',
|
||||
'data' => $globalPredData
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'dates' => $predictionDates,
|
||||
'labels' => $predictionLabels,
|
||||
'data' => $predictionChartData,
|
||||
'total' => $totalPrediksiTersedia
|
||||
];
|
||||
}
|
||||
|
||||
private function generatePieData(): array
|
||||
{
|
||||
$salesData = DataPenjualan::select('jumlah')->get();
|
||||
return [
|
||||
'rendah' => $salesData->filter(fn($item) => $item->jumlah < 10)->count(),
|
||||
'sedang' => $salesData->filter(fn($item) => $item->jumlah >= 10 && $item->jumlah <= 15)->count(),
|
||||
'tinggi' => $salesData->filter(fn($item) => $item->jumlah > 15)->count(),
|
||||
];
|
||||
}
|
||||
|
||||
private function generateAktivitasLogData(Collection $pangkalanList): Collection
|
||||
{
|
||||
$aktivitasPangkalan = [];
|
||||
foreach ($pangkalanList as $pangkalan) {
|
||||
$latestSales = DataPenjualan::where(['user_id' => $pangkalan->id])->orderBy('created_at', 'desc')->first();
|
||||
$latestPred = HasilPrediksi::where(['user_id' => $pangkalan->id])->orderBy('created_at', 'desc')->first();
|
||||
|
||||
if ($latestSales || $latestPred) {
|
||||
$salesTime = $latestSales ? $latestSales->created_at : null;
|
||||
$predTime = $latestPred ? $latestPred->created_at : null;
|
||||
|
||||
$pilihAksi = ($salesTime && $predTime && $salesTime->gt($predTime)) || $latestSales && !$latestPred ? 'sales' : 'prediksi';
|
||||
|
||||
if ($pilihAksi == 'sales') {
|
||||
$aktivitasPangkalan[] = [
|
||||
'name' => $pangkalan->name,
|
||||
'aksi' => 'melakukan input data penjualan',
|
||||
'waktu' => $latestSales->created_at
|
||||
];
|
||||
} else {
|
||||
$aktivitasPangkalan[] = [
|
||||
'name' => $pangkalan->name,
|
||||
'aksi' => 'melakukan prediksi',
|
||||
'waktu' => $latestPred->created_at
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
return collect($aktivitasPangkalan)->sortByDesc(fn($activity) => $activity['waktu'])->take(7);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,162 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\DataPenjualan;
|
||||
use App\Exports\DataPenjualanExport;
|
||||
use App\Exports\DataPenjualanRekapExport;
|
||||
use Illuminate\Http\Request;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class DataPenjualanUserControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
// Mengambil semua pangkalan dengan total hari log datanya
|
||||
$pangkalanList = User::where(['role' => 'user'])
|
||||
->withCount('dataPenjualan')
|
||||
->get();
|
||||
|
||||
// Menghitung status perhatian secara real-time untuk setiap pangkalan di halaman index
|
||||
foreach ($pangkalanList as $pangkalan) {
|
||||
$monthlyData = DataPenjualan::where(['user_id' => $pangkalan->id])
|
||||
->select(DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"), DB::raw("SUM(jumlah) as total"))
|
||||
->groupBy('bulan')
|
||||
->get();
|
||||
|
||||
if ($monthlyData->isEmpty()) {
|
||||
$pangkalan->status_perhatian = 'Belum Ada Transaksi';
|
||||
continue;
|
||||
}
|
||||
|
||||
$totals = $monthlyData->pluck('total');
|
||||
$average = $totals->avg();
|
||||
|
||||
// Hitung Standar Deviasi
|
||||
$variance = 0;
|
||||
foreach ($totals as $t) {
|
||||
$variance += pow(($t - $average), 2);
|
||||
}
|
||||
$stdDev = sqrt($variance / $totals->count());
|
||||
|
||||
// Hitung Koefisien Variasi (CV)
|
||||
$coefficentOfVariation = $average > 0 ? ($stdDev / $average) : 0;
|
||||
|
||||
// Aturan sinkronisasi threshold indikator CV
|
||||
if ($coefficentOfVariation > 0.30) {
|
||||
$pangkalan->status_perhatian = 'PERLU PERHATIAN KHUSUS';
|
||||
} else if ($coefficentOfVariation > 0.15) {
|
||||
$pangkalan->status_perhatian = 'Pantauan Berkala';
|
||||
} else {
|
||||
$pangkalan->status_perhatian = 'Stabil (Aman)';
|
||||
}
|
||||
}
|
||||
|
||||
return view('admin.data-penjualan-user.index', compact('pangkalanList'));
|
||||
}
|
||||
|
||||
public function show(Request $request, $id)
|
||||
{
|
||||
Carbon::setLocale('id');
|
||||
|
||||
$pangkalan = User::where(['role' => 'user'])->findOrFail($id);
|
||||
|
||||
$filterBulanTahun = $request->get('bulan_tahun');
|
||||
$sortOrder = $request->get('sort', 'desc');
|
||||
|
||||
$query = DataPenjualan::where('user_id', $id);
|
||||
|
||||
if ($filterBulanTahun) {
|
||||
$yearMonth = explode('-', $filterBulanTahun);
|
||||
if (count($yearMonth) === 2) {
|
||||
$query->whereYear('tanggal', $yearMonth[0])
|
||||
->whereMonth('tanggal', $yearMonth[1]);
|
||||
}
|
||||
}
|
||||
|
||||
$data_penjualan = $query->orderBy('tanggal', $sortOrder)->get();
|
||||
|
||||
$availableMonths = DataPenjualan::where('user_id', $id)
|
||||
->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month')
|
||||
->groupBy('year', 'month')
|
||||
->orderBy('year', 'desc')
|
||||
->orderBy('month', 'desc')
|
||||
->get()
|
||||
->map(function ($item) {
|
||||
$date = Carbon::createFromDate($item->year, $item->month, 1)->locale('id');
|
||||
return [
|
||||
'value' => $date->format('Y-m'),
|
||||
'label' => $date->translatedFormat('F Y')
|
||||
];
|
||||
});
|
||||
|
||||
// HITUNG ALASAN DETAIL EVALUASI MATRIKS UNTUK DITAMPILKAN DI PANEL VIEW SHOW
|
||||
$allMonthlyData = DataPenjualan::where(['user_id' => $id])
|
||||
->select(DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"), DB::raw("SUM(jumlah) as total"))
|
||||
->groupBy('bulan')
|
||||
->get();
|
||||
|
||||
$statusPenting = 'Stabil (Aman)';
|
||||
$alasanAnalisis = 'Pola permintaan pasar konstan. Alokasi kuota tetap dapat dipertahankan.';
|
||||
$cvPersen = '0%';
|
||||
|
||||
if ($allMonthlyData->isNotEmpty()) {
|
||||
$totals = $allMonthlyData->pluck('total');
|
||||
$average = $totals->avg();
|
||||
|
||||
$variance = 0;
|
||||
foreach ($totals as $t) {
|
||||
$variance += pow(($t - $average), 2);
|
||||
}
|
||||
$stdDev = sqrt($variance / $totals->count());
|
||||
$cv = $average > 0 ? ($stdDev / $average) : 0;
|
||||
$cvPersen = round($cv * 100, 1) . '%';
|
||||
|
||||
if ($cv > 0.30) {
|
||||
$statusPenting = 'PERLU PERHATIAN KHUSUS';
|
||||
$alasanAnalisis = 'Kesenjangan penjualan antarbulan sangat tinggi. Distribusi kuota wajib disesuaikan secara dinamis untuk menghindari kelangkaan atau penumpukan.';
|
||||
} else if ($cv > 0.15) {
|
||||
$statusPenting = 'Pantauan Berkala';
|
||||
$alasanAnalisis = 'Penjualan mengalami fluktuasi tingkat sedang. Diperlukan monitoring per kuartal secara rutin.';
|
||||
}
|
||||
}
|
||||
|
||||
return view('admin.data-penjualan-user.show', compact(
|
||||
'pangkalan',
|
||||
'data_penjualan',
|
||||
'availableMonths',
|
||||
'filterBulanTahun',
|
||||
'sortOrder',
|
||||
'statusPenting',
|
||||
'alasanAnalisis',
|
||||
'cvPersen'
|
||||
));
|
||||
}
|
||||
|
||||
public function export(Request $request, $id)
|
||||
{
|
||||
$pangkalan = User::where(['role' => 'user'])->findOrFail($id);
|
||||
$filterBulanTahun = $request->get('bulan_tahun');
|
||||
|
||||
if ($filterBulanTahun) {
|
||||
$bulanIndo = Carbon::parse($filterBulanTahun . '-01')->locale('id')->translatedFormat('F_Y');
|
||||
$filename = 'Data_Penjualan_' . str_replace(' ', '_', $pangkalan->name) . '_' . $bulanIndo . '.xlsx';
|
||||
} else {
|
||||
$filename = 'Data_Penjualan_' . str_replace(' ', '_', $pangkalan->name) . '_Keseluruhan.xlsx';
|
||||
}
|
||||
|
||||
return Excel::download(new DataPenjualanExport($id, $filterBulanTahun), $filename);
|
||||
}
|
||||
|
||||
public function exportRekapMassal()
|
||||
{
|
||||
$tanggalUnduh = Carbon::now()->format('d-m-Y');
|
||||
$filename = 'Rekap Data Penjualan Pangkalan_Diunduh tgl ' . $tanggalUnduh . '.xlsx';
|
||||
|
||||
return Excel::download(new DataPenjualanRekapExport, $filename);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\HasilPrediksi;
|
||||
use App\Models\DataPenjualan;
|
||||
use App\Models\Helpdesk;
|
||||
use Illuminate\Http\Request;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DataUserControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$users = User::where('role', 'user')
|
||||
->withCount(['hasilPrediksis', 'helpdesks'])
|
||||
->latest()
|
||||
->get();
|
||||
|
||||
return view('admin.data-user.index', compact('users'));
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
|
||||
Carbon::setLocale('id');
|
||||
|
||||
$user = User::withCount(['hasilPrediksis', 'helpdesks'])->findOrFail($id);
|
||||
|
||||
|
||||
$prediksis = HasilPrediksi::where('user_id', $id)
|
||||
->latest()
|
||||
->get()
|
||||
->map(function($item) {
|
||||
return [
|
||||
'jenis' => 'Melakukan Prediksi Stok',
|
||||
'tanggal' => Carbon::parse($item->created_at)->locale('id'),
|
||||
'status' => 'Berhasil',
|
||||
'badge' => 'success',
|
||||
'icon' => 'fas fa-robot text-primary'
|
||||
];
|
||||
});
|
||||
|
||||
$uploads = DataPenjualan::where('user_id', $id)
|
||||
->latest()
|
||||
->get()
|
||||
->map(function($item) {
|
||||
return [
|
||||
'jenis' => 'Update Data Penjualan',
|
||||
'tanggal' => Carbon::parse($item->created_at)->locale('id'),
|
||||
'status' => 'Terbaru',
|
||||
'badge' => 'info',
|
||||
'icon' => 'fas fa-file-upload text-info'
|
||||
];
|
||||
});
|
||||
|
||||
$bantuans = Helpdesk::where('user_id', $id)
|
||||
->latest()
|
||||
->get()
|
||||
->map(function($item) {
|
||||
return [
|
||||
'jenis' => 'Mengirim Tiket Bantuan',
|
||||
'tanggal' => Carbon::parse($item->created_at)->locale('id'),
|
||||
'status' => $item->reply ? 'Selesai' : 'Menunggu',
|
||||
'badge' => $item->reply ? 'success' : 'warning',
|
||||
'icon' => 'fas fa-headset text-warning'
|
||||
];
|
||||
});
|
||||
|
||||
$riwayatAktivitas = collect()
|
||||
->concat($prediksis)
|
||||
->concat($uploads)
|
||||
->concat($bantuans)
|
||||
|
||||
->sortByDesc(function ($aktivitas) {
|
||||
return $aktivitas['tanggal']->timestamp;
|
||||
})
|
||||
->unique(function ($aktivitas) {
|
||||
return $aktivitas['jenis'] . $aktivitas['tanggal']->format('Y-m-d H:i');
|
||||
})
|
||||
->take(10);
|
||||
|
||||
return view('admin.data-user.detail', compact('user', 'riwayatAktivitas'));
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
$user->delete();
|
||||
|
||||
return redirect()->route('admin.data-user')->with('success', 'User berhasil dihapus.');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\HasilPrediksi;
|
||||
use App\Exports\HasilPrediksiExport;
|
||||
use App\Exports\HasilPrediksiRekapExport;
|
||||
use Illuminate\Http\Request;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class HasilPrediksiControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
// Mengambil seluruh data pengguna dengan role user beserta total hari log prediksi
|
||||
$pangkalanList = User::where(['role' => 'user'])
|
||||
->withCount('hasilPrediksi')
|
||||
->get();
|
||||
|
||||
// Hitung status mitigasi proyeksi lonjakan untuk setiap pangkalan secara real-time
|
||||
foreach ($pangkalanList as $pangkalan) {
|
||||
$monthlyData = HasilPrediksi::where(['user_id' => $pangkalan->id])
|
||||
->select(DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"), DB::raw("SUM(estimasi) as total_estimasi"))
|
||||
->groupBy('bulan')
|
||||
->get();
|
||||
|
||||
if ($monthlyData->isEmpty()) {
|
||||
$pangkalan->status_mitigasi = 'Belum Ada Prediksi';
|
||||
continue;
|
||||
}
|
||||
|
||||
// Cari nilai puncak bulanan dan rata-rata prediksi
|
||||
$sortedMonthly = $monthlyData->sortByDesc('total_estimasi');
|
||||
$peakValue = (int)$sortedMonthly->first()->total_estimasi;
|
||||
$averageValue = (int)round($monthlyData->pluck('total_estimasi')->avg());
|
||||
|
||||
// Hitung persentase kenaikan puncak terhadap rata-rata bulanan
|
||||
$persentaseKenaikan = $averageValue > 0 ? (($peakValue - $averageValue) / $averageValue) * 100 : 0;
|
||||
|
||||
// Sinkronisasi dengan aturan baku ambang batas di berkas Excel
|
||||
if ($persentaseKenaikan > 20.0) {
|
||||
$pangkalan->status_mitigasi = 'PERLU PERHATIAN KHUSUS';
|
||||
} else if ($persentaseKenaikan > 10.0) {
|
||||
$pangkalan->status_mitigasi = 'Pantauan Berkala';
|
||||
} else {
|
||||
$pangkalan->status_mitigasi = 'Stabil (Aman)';
|
||||
}
|
||||
}
|
||||
|
||||
return view('admin.hasil-prediksi.index', compact('pangkalanList'));
|
||||
}
|
||||
|
||||
public function show(Request $request, $id)
|
||||
{
|
||||
Carbon::setLocale('id');
|
||||
|
||||
$pangkalan = User::where(['role' => 'user'])->findOrFail($id);
|
||||
|
||||
$filterBulanTahun = $request->get('bulan_tahun');
|
||||
$sortOrder = $request->get('sort', 'desc');
|
||||
|
||||
$query = HasilPrediksi::where('user_id', $id);
|
||||
|
||||
if ($filterBulanTahun) {
|
||||
$yearMonth = explode('-', $filterBulanTahun);
|
||||
if (count($yearMonth) === 2) {
|
||||
$query->whereYear('tanggal', $yearMonth[0])
|
||||
->whereMonth('tanggal', $yearMonth[1]);
|
||||
}
|
||||
}
|
||||
|
||||
$hasil_prediksi = $query->orderBy('tanggal', $sortOrder)->get();
|
||||
|
||||
$availableMonths = HasilPrediksi::where('user_id', $id)
|
||||
->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month')
|
||||
->groupBy('year', 'month')
|
||||
->orderBy('year', 'desc')
|
||||
->orderBy('month', 'desc')
|
||||
->get()
|
||||
->map(function ($item) {
|
||||
$date = Carbon::createFromDate($item->year, $item->month, 1)->locale('id');
|
||||
return [
|
||||
'value' => $date->format('Y-m'),
|
||||
'label' => $date->translatedFormat('F Y')
|
||||
];
|
||||
});
|
||||
|
||||
// LOGIKA PENYUSUNAN DETAIL MITIGASI LONJAKAN UNTUK PANEL UTAMA VIEW SHOW
|
||||
$allMonthlyData = HasilPrediksi::where(['user_id' => $id])
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"),
|
||||
DB::raw("SUM(estimasi) as total_estimasi")
|
||||
)
|
||||
->groupBy('bulan')
|
||||
->get();
|
||||
|
||||
$statusPenting = 'Stabil (Aman)';
|
||||
$alasanAnalisis = 'Proyeksi fluktuasi permintaan cenderung stabil. Alokasi kuota reguler aman.';
|
||||
$persenKenaikanTeks = '0%';
|
||||
|
||||
if ($allMonthlyData->isNotEmpty()) {
|
||||
$sortedMonthly = $allMonthlyData->sortByDesc('total_estimasi');
|
||||
$highestMonthRaw = $sortedMonthly->first()->bulan;
|
||||
|
||||
$highestMonthLabel = Carbon::parse($highestMonthRaw . '-01')->translatedFormat('F Y');
|
||||
$peakValue = (int)$sortedMonthly->first()->total_estimasi;
|
||||
$averageValue = (int)round($allMonthlyData->pluck('total_estimasi')->avg());
|
||||
|
||||
$persentaseKenaikan = $averageValue > 0 ? (($peakValue - $averageValue) / $averageValue) * 100 : 0;
|
||||
$persenKenaikanTeks = round($persentaseKenaikan, 1) . '%';
|
||||
|
||||
if ($persentaseKenaikan > 20.0) {
|
||||
$statusPenting = 'PERLU PERHATIAN KHUSUS';
|
||||
$alasanAnalisis = 'Diproyeksikan mengalami lonjakan permintaan ekstrem sebesar ' . $persenKenaikanTeks . ' pada bulan ' . $highestMonthLabel . '. Alokasi pasokan wajib ditambah mendekati batas atas.';
|
||||
} else if ($persentaseKenaikan > 10.0) {
|
||||
$statusPenting = 'Pantauan Berkala';
|
||||
$alasanAnalisis = 'Terdapat indikasi kenaikan permintaan pasar tingkat sedang pada bulan ' . $highestMonthLabel . '. Diperlukan pemantauan stok berkala.';
|
||||
}
|
||||
}
|
||||
|
||||
return view('admin.hasil-prediksi.show', compact(
|
||||
'pangkalan',
|
||||
'hasil_prediksi',
|
||||
'availableMonths',
|
||||
'filterBulanTahun',
|
||||
'sortOrder',
|
||||
'statusPenting',
|
||||
'alasanAnalisis',
|
||||
'persenKenaikanTeks'
|
||||
));
|
||||
}
|
||||
|
||||
public function export(Request $request, $id)
|
||||
{
|
||||
$pangkalan = User::where(['role' => 'user'])->findOrFail($id);
|
||||
$filterBulanTahun = $request->get('bulan_tahun');
|
||||
|
||||
if ($filterBulanTahun) {
|
||||
$bulanIndo = Carbon::parse($filterBulanTahun . '-01')->locale('id')->translatedFormat('F_Y');
|
||||
$filename = 'Hasil_Prediksi_' . str_replace(' ', '_', $pangkalan->name) . '_' . $bulanIndo . '.xlsx';
|
||||
} else {
|
||||
$filename = 'Hasil_Prediksi_' . str_replace(' ', '_', $pangkalan->name) . '_Keseluruhan.xlsx';
|
||||
}
|
||||
|
||||
return Excel::download(new HasilPrediksiExport($id, $filterBulanTahun), $filename);
|
||||
}
|
||||
|
||||
public function exportRekapMassal()
|
||||
{
|
||||
$tanggalUnduh = Carbon::now()->format('d-m-Y');
|
||||
$filename = 'Rekap Hasil Prediksi Pangkalan_Diunduh tgl ' . $tanggalUnduh . '.xlsx';
|
||||
|
||||
return Excel::download(new HasilPrediksiRekapExport, $filename);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Artikel;
|
||||
|
||||
class ManagementArtikelControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$artikels = Artikel::latest()->get();
|
||||
return view('admin.management-artikel.index', compact('artikels'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'judul' => 'required|string|max:255',
|
||||
'gambar' => 'required|image|mimes:jpeg,png,jpg|max:5120',
|
||||
'deskripsi' => 'required',
|
||||
'sumber' => 'required'
|
||||
]);
|
||||
|
||||
$pathGambar = null;
|
||||
|
||||
if ($request->hasFile('gambar')) {
|
||||
$file = $request->file('gambar');
|
||||
|
||||
$fileName = time() . '_artikel_' . uniqid() . '.' . $file->getClientOriginalExtension();
|
||||
|
||||
$file->move(public_path('uploads/artikel'), $fileName);
|
||||
|
||||
$pathGambar = 'uploads/artikel/' . $fileName;
|
||||
}
|
||||
|
||||
Artikel::create([
|
||||
'judul' => $request->judul,
|
||||
'gambar' => $pathGambar,
|
||||
'deskripsi' => $request->deskripsi,
|
||||
'sumber' => $request->sumber
|
||||
]);
|
||||
|
||||
return back()->with('success', 'Artikel berhasil ditambahkan');
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$artikel = Artikel::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'judul' => 'required|string|max:255',
|
||||
'deskripsi' => 'required',
|
||||
'sumber' => 'required',
|
||||
'gambar' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
|
||||
]);
|
||||
|
||||
$data = [
|
||||
'judul' => $request->judul,
|
||||
'deskripsi' => $request->deskripsi,
|
||||
'sumber' => $request->sumber
|
||||
];
|
||||
|
||||
if ($request->hasFile('gambar')) {
|
||||
if ($artikel->gambar && file_exists(public_path($artikel->gambar))) {
|
||||
@unlink(public_path($artikel->gambar));
|
||||
}
|
||||
|
||||
$file = $request->file('gambar');
|
||||
$fileName = time() . '_artikel_' . uniqid() . '.' . $file->getClientOriginalExtension();
|
||||
|
||||
$file->move(public_path('uploads/artikel'), $fileName);
|
||||
$data['gambar'] = 'uploads/artikel/' . $fileName;
|
||||
}
|
||||
|
||||
$artikel->update($data);
|
||||
|
||||
return back()->with('success', 'Artikel berhasil diupdate');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$artikel = Artikel::findOrFail($id);
|
||||
|
||||
if ($artikel->gambar && file_exists(public_path($artikel->gambar))) {
|
||||
@unlink(public_path($artikel->gambar));
|
||||
}
|
||||
|
||||
$artikel->delete();
|
||||
|
||||
return back()->with('success', 'Artikel berhasil dihapus');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Helpdesk;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ManagementBantuanControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$helpdesks = Helpdesk::with('user')->latest()->get();
|
||||
return view('admin.management-bantuan.index', compact('helpdesks'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$request->validate([
|
||||
'reply' => 'required',
|
||||
'reply_attachment' => 'nullable|image|max:5120'
|
||||
]);
|
||||
|
||||
$helpdesk = Helpdesk::findOrFail($id);
|
||||
|
||||
$data = [
|
||||
'reply' => $request->reply,
|
||||
'status' => 'answered'
|
||||
];
|
||||
|
||||
if ($request->hasFile('reply_attachment')) {
|
||||
if ($helpdesk->reply_attachment && file_exists(public_path($helpdesk->reply_attachment))) {
|
||||
@unlink(public_path($helpdesk->reply_attachment));
|
||||
}
|
||||
|
||||
$file = $request->file('reply_attachment');
|
||||
$fileName = time() . '_reply_' . uniqid() . '.' . $file->getClientOriginalExtension();
|
||||
|
||||
$file->move(public_path('uploads/helpdesk/replies'), $fileName);
|
||||
|
||||
$data['reply_attachment'] = 'uploads/helpdesk/replies/' . $fileName;
|
||||
}
|
||||
|
||||
$helpdesk->update($data);
|
||||
|
||||
return redirect()->back()->with('success', 'Balasan berhasil dikirim.');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$helpdesk = Helpdesk::findOrFail($id);
|
||||
|
||||
if ($helpdesk->attachment && file_exists(public_path($helpdesk->attachment))) {
|
||||
@unlink(public_path($helpdesk->attachment));
|
||||
}
|
||||
|
||||
if ($helpdesk->reply_attachment && file_exists(public_path($helpdesk->reply_attachment))) {
|
||||
@unlink(public_path($helpdesk->reply_attachment));
|
||||
}
|
||||
|
||||
$helpdesk->delete();
|
||||
return redirect()->back()->with('success', 'Pesan bantuan berhasil dihapus.');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Faq;
|
||||
|
||||
class ManagementFaqControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$faqs = Faq::latest()->get();
|
||||
return view('admin.management-faq.index', compact('faqs'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
return view('admin.management-faq.create');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'question' => 'required',
|
||||
'answer' => 'required',
|
||||
]);
|
||||
|
||||
Faq::create($request->all());
|
||||
|
||||
return redirect()->route('admin.management-faq.index')
|
||||
->with('success', 'FAQ berhasil ditambahkan');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$faq = Faq::findOrFail($id);
|
||||
return view('admin.management-faq.edit', compact('faq'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$faq = Faq::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'question' => 'required',
|
||||
'answer' => 'required',
|
||||
]);
|
||||
|
||||
$faq->update($request->all());
|
||||
|
||||
return redirect()->route('admin.management-faq.index')
|
||||
->with('success', 'FAQ berhasil diupdate');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
Faq::destroy($id);
|
||||
|
||||
return redirect()->route('admin.management-faq.index')
|
||||
->with('success', 'FAQ berhasil dihapus');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Auth\LoginRequest;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AuthenticatedSessionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the login view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming authentication request.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
$user = User::where('email', $request->email)->first();
|
||||
|
||||
if (!$user) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => 'Email tidak ditemukan, silahkan lakukan pendaftaran akun terlebih dahulu.',
|
||||
]);
|
||||
}
|
||||
|
||||
if (!Hash::check($request->password, $user->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'password' => 'Password dari akun tersebut salah.',
|
||||
]);
|
||||
}
|
||||
|
||||
Auth::login($user, $request->boolean('remember'));
|
||||
$request->session()->regenerate();
|
||||
|
||||
if ($request->user()->role === 'admin') {
|
||||
return redirect()->intended(route('admin.dashboard'))->with('success_login', true);
|
||||
}
|
||||
|
||||
return redirect()->intended(route('user.dashboard'))->with('success_login', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy an authenticated session.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
Auth::guard('web')->logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect('/');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ConfirmablePasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the confirm password view.
|
||||
*/
|
||||
public function show(): View
|
||||
{
|
||||
return view('auth.confirm-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm the user's password.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if (! Auth::guard('web')->validate([
|
||||
'email' => $request->user()->email,
|
||||
'password' => $request->password,
|
||||
])) {
|
||||
throw ValidationException::withMessages([
|
||||
'password' => __('auth.password'),
|
||||
]);
|
||||
}
|
||||
|
||||
$request->session()->put('auth.password_confirmed_at', time());
|
||||
|
||||
return redirect()->intended(route('dashboard', absolute: false));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class EmailVerificationNotificationController extends Controller
|
||||
{
|
||||
/**
|
||||
* Send a new email verification notification.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
$url = $request->user()->role === 'admin'
|
||||
? route('admin.dashboard')
|
||||
: route('user.dashboard');
|
||||
|
||||
return redirect()->intended($url);
|
||||
}
|
||||
|
||||
$request->user()->sendEmailVerificationNotification();
|
||||
|
||||
return back()->with('status', 'verification-link-sent');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class EmailVerificationPromptController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the email verification prompt.
|
||||
*/
|
||||
public function __invoke(Request $request): RedirectResponse|View
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
$url = $request->user()->role === 'admin' ? route('admin.dashboard') : route('user.dashboard');
|
||||
return redirect()->intended($url);
|
||||
}
|
||||
|
||||
return view('auth.verify-email');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Events\PasswordReset;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class NewPasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the password reset view.
|
||||
*/
|
||||
public function create(Request $request): View
|
||||
{
|
||||
return view('auth.reset-password', ['request' => $request]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming new password request.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'token' => ['required'],
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'confirmed', Rules\Password::min(8)->mixedCase()->numbers()->symbols()],
|
||||
]);
|
||||
|
||||
$status = Password::reset(
|
||||
$request->only('email', 'password', 'password_confirmation', 'token'),
|
||||
function (User $user) use ($request) {
|
||||
$user->forceFill([
|
||||
'password' => Hash::make($request->password),
|
||||
'remember_token' => Str::random(60),
|
||||
])->save();
|
||||
|
||||
event(new PasswordReset($user));
|
||||
}
|
||||
);
|
||||
|
||||
return $status == Password::PASSWORD_RESET
|
||||
? redirect()->route('login')->with('reset_success', 'Password Anda berhasil diperbarui. Silakan login kembali dengan password baru Anda.')
|
||||
: back()->withInput($request->only('email'))
|
||||
->withErrors(['email' => __($status)]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class PasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Update the user's password.
|
||||
*/
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validateWithBag('updatePassword', [
|
||||
'current_password' => ['required', 'current_password'],
|
||||
'password' => ['required', Password::defaults(), 'confirmed'],
|
||||
]);
|
||||
|
||||
$request->user()->update([
|
||||
'password' => Hash::make($validated['password']),
|
||||
]);
|
||||
|
||||
return back()->with('status', 'password-updated');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class PasswordResetLinkController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the password reset link request view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.forgot-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming password reset link request.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
]);
|
||||
|
||||
$userExists = User::where('email', $request->email)->exists();
|
||||
|
||||
if (!$userExists) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => 'Email tersebut belum terdaftar, pastikan penulisan email benar.',
|
||||
]);
|
||||
}
|
||||
|
||||
$status = Password::sendResetLink(
|
||||
$request->only('email')
|
||||
);
|
||||
|
||||
return $status == Password::RESET_LINK_SENT
|
||||
? back()->with('status', 'Link reset password telah dikirim ke email Anda. Silakan periksa email Anda untuk instruksi lebih lanjut.!')
|
||||
: back()->withInput($request->only('email'))
|
||||
->withErrors(['email' => __($status)]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class RegisteredUserController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the registration view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming registration request.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'nama_pangkalan' => ['required', 'string', 'max:255'],
|
||||
'alamat' => ['required', 'string'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
|
||||
'password' => ['required', 'confirmed', Rules\Password::defaults()],
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'nama_pangkalan' => $request->nama_pangkalan,
|
||||
'alamat' => $request->alamat,
|
||||
'email' => $request->email,
|
||||
'password' => Hash::make($request->password),
|
||||
'role' => 'user',
|
||||
]);
|
||||
|
||||
event(new Registered($user));
|
||||
|
||||
Auth::login($user);
|
||||
|
||||
return redirect()->route('user.dashboard')->with('success_register', 'Pendaftaran berhasil! Silakan cek email Anda untuk verifikasi akun sebelum login.');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Auth\Events\Verified;
|
||||
use Illuminate\Foundation\Auth\EmailVerificationRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class VerifyEmailController extends Controller
|
||||
{
|
||||
public function __invoke(EmailVerificationRequest $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
$url = $request->user()->role === 'admin' ? 'admin.dashboard' : 'user.dashboard';
|
||||
return redirect()->intended(route($url, absolute: false));
|
||||
}
|
||||
|
||||
if ($request->user()->markEmailAsVerified()) {
|
||||
event(new Verified($request->user()));
|
||||
}
|
||||
|
||||
if ($request->user()->role === 'user') {
|
||||
return redirect()->route('user.bantuan')->with('verified_first_time', true);
|
||||
}
|
||||
|
||||
return redirect()->route('admin.dashboard');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Faq;
|
||||
use App\Models\Artikel;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class LandingControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$faqs = Faq::latest()->take(5)->get();
|
||||
$artikels = Artikel::latest()->take(7)->get();
|
||||
|
||||
return view('landing-page.welcome', compact('faqs', 'artikels'));
|
||||
}
|
||||
|
||||
public function sendContactMail(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'subject' => 'required|string|max:100',
|
||||
'email' => 'required|email',
|
||||
'message' => 'required|string'
|
||||
]);
|
||||
|
||||
try {
|
||||
$senderEmail = $request->email;
|
||||
$msgSubject = $request->subject;
|
||||
$msgContent = $request->message;
|
||||
|
||||
$emailBody = "Halo Admin PeGas,\n\nAnda menerima pesan baru dari formulir kontak Landing Page.\n\n";
|
||||
$emailBody .= "Pengirim: " . $msgSubject . " (" . $senderEmail . ")\n";
|
||||
$emailBody .= "Isi Pesan:\n" . $msgContent . "\n\n";
|
||||
$emailBody .= "Sistem Informasi Manajemen Stok LPG PeGas 2026.";
|
||||
|
||||
Mail::raw($emailBody, function ($message) use ($senderEmail, $msgSubject) {
|
||||
$message->to('pegaslpgsystem@gmail.com')
|
||||
->from($senderEmail)
|
||||
->subject("MESSAGES: " . $msgSubject);
|
||||
});
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Pesan berhasil dikirim ke email pegaslpgsystem@gmail.com'
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Gagal mengirim pesan: ' . $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\ProfileUpdateRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Redirect;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the user's profile form.
|
||||
*/
|
||||
public function edit(Request $request): View
|
||||
{
|
||||
return view('profile.edit', [
|
||||
'user' => $request->user(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's profile information.
|
||||
*/
|
||||
public function update(ProfileUpdateRequest $request): RedirectResponse
|
||||
{
|
||||
$request->user()->fill($request->validated());
|
||||
|
||||
if ($request->user()->isDirty('email')) {
|
||||
$request->user()->email_verified_at = null;
|
||||
}
|
||||
|
||||
$request->user()->save();
|
||||
|
||||
return Redirect::route('profile.edit')->with('status', 'profile-updated');
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the user's account.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validateWithBag('userDeletion', [
|
||||
'password' => ['required', 'current_password'],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
Auth::logout();
|
||||
|
||||
$user->delete();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return Redirect::to('/');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Helpdesk;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class BantuanControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$helpdesks = Helpdesk::where('user_id', Auth::id())->latest()->get();
|
||||
|
||||
return view('user.bantuan.index', compact('helpdesks'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'message' => 'required',
|
||||
'attachment' => 'nullable|mimes:jpg,jpeg,png|max:5120'
|
||||
], [
|
||||
'attachment.mimes' => 'Format file tidak didukung. Hanya menerima file JPG, JPEG, atau PNG.',
|
||||
'attachment.max' => 'Ukuran gambar terlalu besar. Maksimal ukuran file adalah 5 MB.'
|
||||
]);
|
||||
|
||||
$filePath = null;
|
||||
|
||||
try {
|
||||
if ($request->hasFile('attachment')) {
|
||||
$file = $request->file('attachment');
|
||||
|
||||
$fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
|
||||
|
||||
$file->move(public_path('uploads/helpdesk'), $fileName);
|
||||
|
||||
$filePath = 'uploads/helpdesk/' . $fileName;
|
||||
}
|
||||
|
||||
Helpdesk::create([
|
||||
'user_id' => Auth::id(),
|
||||
'message' => $request->message,
|
||||
'attachment' => $filePath,
|
||||
'status' => 'pending'
|
||||
]);
|
||||
|
||||
return back()->with('success', 'Pesan berhasil dikirim');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
dd("Gagal menyimpan data ke database karena: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\DataPenjualan;
|
||||
use App\Models\HasilPrediksi;
|
||||
use App\Models\Helpdesk;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$userId = Auth::id();
|
||||
$besok = Carbon::tomorrow()->format('Y-m-d');
|
||||
|
||||
$totalPenjualan = DataPenjualan::where('user_id', $userId)->sum('jumlah');
|
||||
$estimasiBesok = HasilPrediksi::where('user_id', $userId)->where('tanggal', $besok)->first();
|
||||
$jumlahRiwayat = HasilPrediksi::where('user_id', $userId)
|
||||
->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month')
|
||||
->groupBy('year', 'month')->get()->count();
|
||||
$jumlahHelpdesk = Helpdesk::where('user_id', $userId)->count();
|
||||
|
||||
$chartHistori = DataPenjualan::where('user_id', $userId)->orderBy('tanggal', 'desc')->take(7)->get()->reverse();
|
||||
$chartPrediksi = HasilPrediksi::where('user_id', $userId)->orderBy('tanggal', 'asc')->take(15)->get();
|
||||
|
||||
$penjualan = DataPenjualan::where('user_id', $userId)->get();
|
||||
$distribusi = [
|
||||
'Rendah (<10)' => $penjualan->where('jumlah', '<', 10)->count(),
|
||||
'Sedang (10-15)' => $penjualan->whereBetween('jumlah', [10, 15])->count(),
|
||||
'Tinggi (>15)' => $penjualan->where('jumlah', '>', 15)->count(),
|
||||
];
|
||||
|
||||
return view('user.dashboard.index', compact(
|
||||
'totalPenjualan', 'estimasiBesok', 'jumlahRiwayat', 'jumlahHelpdesk',
|
||||
'chartHistori', 'chartPrediksi', 'distribusi'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\DataPenjualan;
|
||||
use App\Imports\DataPenjualanImport;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class MasterDataControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
\Carbon\Carbon::setLocale('id');
|
||||
|
||||
$user_id = Auth::id();
|
||||
|
||||
$data_per_bulan = DataPenjualan::where('user_id', $user_id)
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan_tahun"),
|
||||
DB::raw("SUM(jumlah) as total_jumlah"),
|
||||
DB::raw("COUNT(tanggal) as jumlah_hari")
|
||||
)
|
||||
->groupBy('bulan_tahun')
|
||||
->orderBy('bulan_tahun', 'desc')
|
||||
->get();
|
||||
|
||||
$data_penjualan = DataPenjualan::where('user_id', $user_id)
|
||||
->orderBy('tanggal', 'desc')
|
||||
->get();
|
||||
|
||||
$last_data = DataPenjualan::where('user_id', $user_id)
|
||||
->orderBy('tanggal', 'desc')
|
||||
->first();
|
||||
|
||||
return view('user.masterdata.index', compact('data_per_bulan', 'data_penjualan', 'last_data'));
|
||||
}
|
||||
|
||||
public function updateMassal(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'ids' => 'required|array',
|
||||
'jumlah' => 'required|array'
|
||||
]);
|
||||
|
||||
$updatedDates = [];
|
||||
foreach ($request->ids as $key => $id) {
|
||||
$data = DataPenjualan::where('id', $id)->where('user_id', Auth::id())->first();
|
||||
if ($data && $data->jumlah != $request->jumlah[$key]) {
|
||||
$data->update(['jumlah' => $request->jumlah[$key]]);
|
||||
$updatedDates[] = Carbon::parse($data->tanggal)->translatedFormat('d F Y');
|
||||
}
|
||||
}
|
||||
|
||||
Session::forget('prediction_ready');
|
||||
|
||||
if (count($updatedDates) > 0) {
|
||||
return redirect()->back()->with('success', 'Data berhasil diperbarui.');
|
||||
}
|
||||
|
||||
return redirect()->back()->with('info', 'Tidak ada perubahan data.');
|
||||
}
|
||||
|
||||
public function destroyBulan(string $bulan_tahun)
|
||||
{
|
||||
DataPenjualan::where('user_id', Auth::id())
|
||||
->where(DB::raw("DATE_FORMAT(tanggal, '%Y-%m')"), $bulan_tahun)
|
||||
->delete();
|
||||
|
||||
Session::forget('prediction_ready');
|
||||
return redirect()->back()->with('success', "Data bulan tersebut berhasil dihapus.");
|
||||
}
|
||||
|
||||
// Perbaikan Backend: Penanganan validasi wajib isi dan konversi otomatis nilai kosong ke angka 0
|
||||
public function storeBulan(Request $request)
|
||||
{
|
||||
// Memastikan array tanggal dan jumlah wajib dikirimkan oleh sistem
|
||||
$request->validate([
|
||||
'tanggal' => 'required|array',
|
||||
'jumlah' => 'required|array'
|
||||
]);
|
||||
|
||||
$user_id = Auth::id();
|
||||
$dataToInsert = [];
|
||||
|
||||
foreach ($request->tanggal as $key => $tgl) {
|
||||
$jml = $request->jumlah[$key];
|
||||
|
||||
// ATURAN VALIDASI AMAN: Jika kolom tidak diisi atau kosong, paksa isi dengan angka 0
|
||||
if ($jml === null || $jml === '') {
|
||||
$jml = 0;
|
||||
}
|
||||
|
||||
// Validasi jaminan anti-duplikat transaksi pada tanggal yang sama untuk pangkalan terkait
|
||||
$exists = DataPenjualan::where('user_id', $user_id)->where('tanggal', $tgl)->exists();
|
||||
if (!$exists) {
|
||||
$dataToInsert[] = [
|
||||
'user_id' => $user_id,
|
||||
'tanggal' => $tgl,
|
||||
'jumlah' => $jml,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (count($dataToInsert) > 0) {
|
||||
DataPenjualan::insert($dataToInsert);
|
||||
// Membersihkan session verifikasi prediksi agar data baru dihitung ulang
|
||||
Session::forget('prediction_ready');
|
||||
return redirect()->back()->with('success', "Seluruh baris data bulanan berhasil disimpan ke database.");
|
||||
}
|
||||
|
||||
return redirect()->back()->with('error', 'Gagal memproses data. Baris tanggal untuk periode bulan terpilih sudah terdaftar di sistem.');
|
||||
}
|
||||
|
||||
public function import(Request $request) {
|
||||
$request->validate(['file_excel' => 'required|mimes:xlsx,xls,csv|max:5120']);
|
||||
try {
|
||||
Excel::import(new DataPenjualanImport, $request->file('file_excel'));
|
||||
Session::forget('prediction_ready');
|
||||
return redirect()->back()->with('success', 'Import Berhasil!');
|
||||
} catch (\Exception $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function siapkanPrediksi() {
|
||||
if (DataPenjualan::where('user_id', Auth::id())->count() < 365) {
|
||||
return redirect()->back()->with('error', 'Minimal data harus 365 hari.');
|
||||
}
|
||||
Session::put('prediction_ready', true);
|
||||
return redirect()->back()->with('success', 'Data diverifikasi.');
|
||||
}
|
||||
|
||||
public function deleteAll() {
|
||||
DataPenjualan::where('user_id', Auth::id())->delete();
|
||||
Session::forget('prediction_ready');
|
||||
return redirect()->back()->with('success', 'Data dikosongkan.');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,256 @@
|
|||
<?php
|
||||
|
||||
// namespace App\Http\Controllers\User;
|
||||
|
||||
// use App\Http\Controllers\Controller;
|
||||
// use Illuminate\Support\Facades\Http;
|
||||
// use Illuminate\Support\Facades\Auth;
|
||||
// use Illuminate\Support\Facades\Session;
|
||||
// use App\Models\DataPenjualan;
|
||||
// use App\Models\HasilPrediksi;
|
||||
// use Carbon\Carbon;
|
||||
|
||||
// class PrediksiControllers extends Controller
|
||||
// {
|
||||
// public function index()
|
||||
// {
|
||||
// $count = DataPenjualan::where('user_id', Auth::id())->count();
|
||||
|
||||
// $is_verified = $count >= 365;
|
||||
|
||||
// $prediction_ready = $this->checkPredictionStatus();
|
||||
|
||||
// $hasilPrediksi = HasilPrediksi::where('user_id', Auth::id())
|
||||
// ->orderBy('tanggal', 'asc')
|
||||
// ->get();
|
||||
|
||||
// return view('user.prediksi.index', compact(
|
||||
// 'is_verified',
|
||||
// 'count',
|
||||
// 'hasilPrediksi',
|
||||
// 'prediction_ready'
|
||||
// ));
|
||||
// }
|
||||
|
||||
// private function checkPredictionStatus()
|
||||
// {
|
||||
// return Session::get('prediction_ready', false);
|
||||
// }
|
||||
|
||||
// public function getForecast()
|
||||
// {
|
||||
// try {
|
||||
|
||||
// $count = DataPenjualan::where('user_id', Auth::id())->count();
|
||||
|
||||
// if ($count < 365) {
|
||||
|
||||
// return response()->json([
|
||||
// 'error' => 'Minimal data penjualan harus 365 hari.'
|
||||
// ], 400);
|
||||
// }
|
||||
|
||||
// if (!$this->checkPredictionStatus()) {
|
||||
|
||||
// return response()->json([
|
||||
// 'error' => 'Ada data baru. Silakan klik tombol "Siapkan Prediksi" terlebih dahulu pada menu Master Data.'
|
||||
// ], 400);
|
||||
// }
|
||||
|
||||
// $userData = DataPenjualan::where('user_id', Auth::id())
|
||||
// ->orderBy('tanggal', 'asc')
|
||||
// ->get(['tanggal', 'jumlah'])
|
||||
// ->map(fn($item) => [
|
||||
// 'tanggal' => Carbon::parse($item->tanggal)->format('Y-m-d'),
|
||||
// 'jumlah' => $item->jumlah
|
||||
// ]);
|
||||
|
||||
// $response = Http::timeout(200)->post(
|
||||
// "http://127.0.0.1:5000/predict",
|
||||
// [
|
||||
// 'days' => 180,
|
||||
// 'user_data' => $userData
|
||||
// ]
|
||||
// );
|
||||
|
||||
// if ($response->successful()) {
|
||||
|
||||
// $predictions = $response->json();
|
||||
|
||||
// HasilPrediksi::where('user_id', Auth::id())->delete();
|
||||
|
||||
// foreach ($predictions as $p) {
|
||||
|
||||
// HasilPrediksi::create([
|
||||
// 'user_id' => Auth::id(),
|
||||
// 'tanggal' => $p['ds'],
|
||||
// 'estimasi' => (int) $p['yhat'],
|
||||
// 'batas_atas' => (int) $p['yhat_upper'],
|
||||
// 'batas_bawah' => (int) $p['yhat_lower'],
|
||||
// ]);
|
||||
// }
|
||||
|
||||
// Session::forget('prediction_ready');
|
||||
|
||||
// return response()->json([
|
||||
// 'success' => true
|
||||
// ]);
|
||||
// }
|
||||
|
||||
// return response()->json([
|
||||
// 'error' => 'Gagal menghubungi server Flask.'
|
||||
// ], 500);
|
||||
|
||||
// } catch (\Exception $e) {
|
||||
|
||||
// return response()->json([
|
||||
// 'error' => $e->getMessage()
|
||||
// ], 500);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Session;
|
||||
use App\Models\DataPenjualan;
|
||||
use App\Models\HasilPrediksi;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class PrediksiControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$count = DataPenjualan::where('user_id', Auth::id())->count();
|
||||
|
||||
$is_verified = $count >= 365;
|
||||
|
||||
$prediction_ready = $this->checkPredictionStatus();
|
||||
|
||||
$hasilPrediksi = HasilPrediksi::where('user_id', Auth::id())
|
||||
->orderBy('tanggal', 'asc')
|
||||
->get();
|
||||
|
||||
return view('user.prediksi.index', compact(
|
||||
'is_verified',
|
||||
'count',
|
||||
'hasilPrediksi',
|
||||
'prediction_ready'
|
||||
));
|
||||
}
|
||||
|
||||
private function checkPredictionStatus()
|
||||
{
|
||||
return Session::get('prediction_ready', false);
|
||||
}
|
||||
|
||||
// fungsi cek ping
|
||||
public function checkFlaskStatus()
|
||||
{
|
||||
try {
|
||||
$flaskBaseUrl = env('FLASK_URL');
|
||||
|
||||
// Mengirim request kosong/ringan ke server Flask dengan timeout cepat (5 detik)
|
||||
$response = Http::timeout(5)->get($flaskBaseUrl . "/predict");
|
||||
|
||||
// Jika server terhubung
|
||||
if ($response->status() === 405 || $response->successful()) {
|
||||
return response()->json([
|
||||
'status' => 'connected',
|
||||
'message' => 'Server Prediksi Berhasil Terhubung'
|
||||
]);
|
||||
}
|
||||
|
||||
// Jika server merespon tapi status servernya crash (500, dll)
|
||||
return response()->json([
|
||||
'status' => 'error_response',
|
||||
'message' => 'Server Prediksi Ada tapi Gagal Dihubungi'
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
// Jika RTO atau host ngrok tidak ditemukan / offline
|
||||
return response()->json([
|
||||
'status' => 'not_found',
|
||||
'message' => 'Server Prediksi Tidak Ditemukan (Offline)'
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function getForecast()
|
||||
{
|
||||
try {
|
||||
|
||||
$count = DataPenjualan::where('user_id', Auth::id())->count();
|
||||
|
||||
if ($count < 365) {
|
||||
|
||||
return response()->json([
|
||||
'error' => 'Minimal data penjualan harus 365 hari.'
|
||||
], 400);
|
||||
}
|
||||
|
||||
if (!$this->checkPredictionStatus()) {
|
||||
|
||||
return response()->json([
|
||||
'error' => 'Ada data baru. Silakan klik tombol "Siapkan Prediksi" terlebih dahulu pada menu Master Data.'
|
||||
], 400);
|
||||
}
|
||||
|
||||
$userData = DataPenjualan::where('user_id', Auth::id())
|
||||
->orderBy('tanggal', 'asc')
|
||||
->get(['tanggal', 'jumlah'])
|
||||
->map(fn($item) => [
|
||||
'tanggal' => Carbon::parse($item->tanggal)->format('Y-m-d'),
|
||||
'jumlah' => $item->jumlah
|
||||
]);
|
||||
|
||||
$flaskBaseUrl = env('FLASK_URL');
|
||||
|
||||
$response = Http::timeout(200)->post(
|
||||
$flaskBaseUrl . "/predict",
|
||||
[
|
||||
'days' => 180,
|
||||
'user_data' => $userData
|
||||
]
|
||||
);
|
||||
|
||||
if ($response->successful()) {
|
||||
|
||||
$predictions = $response->json();
|
||||
|
||||
HasilPrediksi::where('user_id', Auth::id())->delete();
|
||||
|
||||
foreach ($predictions as $p) {
|
||||
|
||||
HasilPrediksi::create([
|
||||
'user_id' => Auth::id(),
|
||||
'tanggal' => $p['ds'],
|
||||
'estimasi' => (int) $p['yhat'],
|
||||
'batas_atas' => (int) $p['yhat_upper'],
|
||||
'batas_bawah' => (int) $p['yhat_lower'],
|
||||
]);
|
||||
}
|
||||
|
||||
Session::forget('prediction_ready');
|
||||
|
||||
return response()->json([
|
||||
'success' => true
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'error' => 'Gagal menghubungi server Flask. Pastikan URL Flask sudah benar dan server Flask sedang berjalan.'
|
||||
], 500);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
|
||||
return response()->json([
|
||||
'error' => 'Server Flask tidak dapat ditemukan.'
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\User;
|
||||
|
||||
class ProfileControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return view('user.profile.index');
|
||||
}
|
||||
|
||||
public function update(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required',
|
||||
'nama_pangkalan' => 'required',
|
||||
'alamat' => 'required',
|
||||
'email' => 'required|email|unique:users,email,' . Auth::id(),
|
||||
]);
|
||||
|
||||
$user = User::findOrFail(Auth::id());
|
||||
|
||||
$user->update([
|
||||
'name' => $request->name,
|
||||
'nama_pangkalan' => $request->nama_pangkalan,
|
||||
'alamat' => $request->alamat,
|
||||
'email' => $request->email,
|
||||
]);
|
||||
|
||||
return back()->with('success', 'Profil berhasil diperbarui');
|
||||
}
|
||||
|
||||
public function updatePassword(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'password' => 'required|min:8|confirmed'
|
||||
]);
|
||||
|
||||
$user = User::findOrFail(Auth::id());
|
||||
|
||||
$user->update([
|
||||
'password' => Hash::make($request->password)
|
||||
]);
|
||||
|
||||
return back()->with('success', 'Password berhasil diubah');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\HasilPrediksi;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use App\Exports\PrediksiExport;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class RiwayatControllers extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$riwayat = HasilPrediksi::where('user_id', Auth::id())
|
||||
->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month, count(*) as total_hari')
|
||||
->groupBy('year', 'month')
|
||||
->orderBy('year', 'asc')
|
||||
->orderBy('month', 'asc')
|
||||
->get();
|
||||
|
||||
return view('user.riwayat.index', compact('riwayat'));
|
||||
}
|
||||
|
||||
public function exportExcel($year, $month)
|
||||
{
|
||||
$year = (int) $year;
|
||||
$month = (int) $month;
|
||||
|
||||
$nama_bulan = Carbon::create()->month($month)->locale('id')->monthName;
|
||||
$nama_file = "Laporan_Prediksi_{$nama_bulan}_{$year}.xlsx";
|
||||
|
||||
return Excel::download(new PrediksiExport($year, $month), $nama_file);
|
||||
}
|
||||
|
||||
public function destroy($year, $month)
|
||||
{
|
||||
try {
|
||||
$year = (int) $year;
|
||||
$month = (int) $month;
|
||||
|
||||
HasilPrediksi::where('user_id', Auth::id())
|
||||
->whereRaw('YEAR(tanggal) = ?', [$year])
|
||||
->whereRaw('MONTH(tanggal) = ?', [$month])
|
||||
->delete();
|
||||
|
||||
return response()->json(['success' => 'Data prediksi bulan tersebut berhasil dihapus.']);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json(['error' => 'Gagal menghapus data.'], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests\Auth;
|
||||
|
||||
use Illuminate\Auth\Events\Lockout;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LoginRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to authenticate the request's credentials.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function authenticate(): void
|
||||
{
|
||||
$this->ensureIsNotRateLimited();
|
||||
|
||||
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
|
||||
RateLimiter::hit($this->throttleKey());
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => trans('auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($this->throttleKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the login request is not rate limited.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function ensureIsNotRateLimited(): void
|
||||
{
|
||||
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event(new Lockout($this));
|
||||
|
||||
$seconds = RateLimiter::availableIn($this->throttleKey());
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => trans('auth.throttle', [
|
||||
'seconds' => $seconds,
|
||||
'minutes' => ceil($seconds / 60),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the rate limiting throttle key for the request.
|
||||
*/
|
||||
public function throttleKey(): string
|
||||
{
|
||||
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ProfileUpdateRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => [
|
||||
'required',
|
||||
'string',
|
||||
'lowercase',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique(User::class)->ignore($this->user()->id),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
|
||||
namespace App\Imports;
|
||||
|
||||
use App\Models\DataPenjualan;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Exception;
|
||||
use Maatwebsite\Excel\Concerns\ToModel;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadingRow;
|
||||
|
||||
class DataPenjualanImport implements ToModel, WithHeadingRow
|
||||
{
|
||||
private bool $headerChecked = false;
|
||||
private array $duplicatedMonths = [];
|
||||
private array $existingDates = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
// Ambil semua tanggal milik user yang sudah ada di database untuk pencocokan cepat
|
||||
$this->existingDates = DataPenjualan::where('user_id', Auth::id())
|
||||
->pluck('tanggal')
|
||||
->toArray();
|
||||
}
|
||||
|
||||
public function model(array $row)
|
||||
{
|
||||
// Normalisasi header Excel
|
||||
$row = array_combine(
|
||||
array_map(fn($key) => trim(strtolower($key ?? '')), array_keys($row)),
|
||||
array_values($row)
|
||||
);
|
||||
|
||||
if (!$this->headerChecked) {
|
||||
$requiredHeaders = ['tanggal_penjualan', 'jumlah'];
|
||||
foreach ($requiredHeaders as $header) {
|
||||
if (!in_array($header, array_keys($row))) {
|
||||
throw new Exception("Header tidak sesuai. Gunakan kolom: tanggal_penjualan & jumlah.");
|
||||
}
|
||||
}
|
||||
$this->headerChecked = true;
|
||||
}
|
||||
|
||||
if (empty($row['tanggal_penjualan'])) return null;
|
||||
|
||||
$tanggalStr = $this->transformDate($row['tanggal_penjualan']);
|
||||
if (!$tanggalStr) return null;
|
||||
|
||||
$currentDate = Carbon::parse($tanggalStr);
|
||||
$bulanTahunReadable = $currentDate->translatedFormat('F Y');
|
||||
|
||||
// Cek jika tanggal pada baris excel ini sudah terdaftar di database sistem
|
||||
if (in_array($tanggalStr, $this->existingDates)) {
|
||||
if (!in_array($bulanTahunReadable, $this->duplicatedMonths)) {
|
||||
$this->duplicatedMonths[] = $bulanTahunReadable;
|
||||
}
|
||||
return null; // Skip baris ini, lanjut periksa baris berikutnya
|
||||
}
|
||||
|
||||
return new DataPenjualan([
|
||||
'user_id' => Auth::id(),
|
||||
'tanggal' => $tanggalStr,
|
||||
'jumlah' => $row['jumlah'],
|
||||
]);
|
||||
}
|
||||
|
||||
private function transformDate($value)
|
||||
{
|
||||
try {
|
||||
if (is_numeric($value)) {
|
||||
return Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value))->format('Y-m-d');
|
||||
}
|
||||
return Carbon::parse($value)->format('Y-m-d');
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destructor / Fungsi Akhir untuk melempar daftar bulan yang bentrok ke Controller
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if (!empty($this->duplicatedMonths)) {
|
||||
$listBulan = implode(', ', $this->duplicatedMonths);
|
||||
throw new Exception("Data di Excel ini sudah ada pada sistem untuk periode: {$listBulan}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Artikel extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'judul',
|
||||
'gambar',
|
||||
'deskripsi',
|
||||
'sumber'
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class DataPenjualan extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'data_penjualan';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'tanggal',
|
||||
'jumlah',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'tanggal' => 'date',
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Faq extends Model
|
||||
{
|
||||
protected $fillable = ['question', 'answer'];
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class HasilPrediksi extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'hasil_prediksi';
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'tanggal',
|
||||
'estimasi',
|
||||
'batas_atas',
|
||||
'batas_bawah',
|
||||
];
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Helpdesk extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'message',
|
||||
'attachment',
|
||||
'reply',
|
||||
'reply_attachment',
|
||||
'status'
|
||||
];
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
|
||||
class User extends Authenticatable implements MustVerifyEmail
|
||||
{
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* UUID settings
|
||||
*/
|
||||
public $incrementing = false;
|
||||
protected $keyType = 'string';
|
||||
|
||||
/**
|
||||
* Boot function untuk generate UUID otomatis
|
||||
*/
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($user) {
|
||||
if (!$user->id) {
|
||||
$user->id = (string) Str::uuid();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Mass assignable
|
||||
*/
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'nama_pangkalan',
|
||||
'alamat',
|
||||
'role',
|
||||
];
|
||||
|
||||
/**
|
||||
* Hidden attributes
|
||||
*/
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
];
|
||||
|
||||
/**
|
||||
* Casts
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
|
||||
public function dataPenjualan()
|
||||
{
|
||||
return $this->hasMany(DataPenjualan::class, 'user_id');
|
||||
}
|
||||
|
||||
public function hasilPrediksis() {
|
||||
return $this->hasMany(HasilPrediksi::class, 'user_id');
|
||||
}
|
||||
|
||||
public function helpdesks() {
|
||||
return $this->hasMany(Helpdesk::class, 'user_id');
|
||||
}
|
||||
|
||||
public function hasilPrediksi()
|
||||
{
|
||||
return $this->hasMany(HasilPrediksi::class, 'user_id');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Auth\Notifications\VerifyEmail;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
ResetPassword::toMailUsing(function (object $notifiable, string $token) {
|
||||
$url = url(route('password.reset', [
|
||||
'token' => $token,
|
||||
'email' => $notifiable->getEmailForPasswordReset(),
|
||||
], false));
|
||||
|
||||
return (new MailMessage)
|
||||
->subject('Atur Ulang Password Akun PeGas Anda')
|
||||
->greeting('Halo!')
|
||||
->line('Kami menerima permintaan untuk mengatur ulang kata sandi (password) akun PeGas Anda. Silakan klik tombol di bawah ini untuk melanjutkan:')
|
||||
->action('Atur Ulang Password', $url)
|
||||
->line('Tautan reset password ini hanya berlaku selama 60 menit.')
|
||||
->line('Jika Anda tidak merasa melakukan permintaan ini, abaikan saja email ini dan password Anda akan tetap aman.')
|
||||
->salutation('Salam hangat,' . "\n" . 'Tim Pengembang PeGas');
|
||||
});
|
||||
|
||||
VerifyEmail::toMailUsing(function (object $notifiable, string $url) {
|
||||
return (new MailMessage)
|
||||
->subject('Verifikasi Alamat Email Akun PeGas')
|
||||
->greeting('Selamat Datang di PeGas!')
|
||||
->line('Terima kasih telah melakukan pendaftaran. Langkah terakhir sebelum Anda dapat menggunakan sistem sepenuhnya adalah memverifikasi alamat email Anda.')
|
||||
->line('Silakan klik tombol di bawah ini untuk mengaktifkan akun Anda:')
|
||||
->action('Verifikasi Email Saya', $url)
|
||||
->line('Jika Anda tidak merasa melakukan pendaftaran akun di platform PeGas, Anda tidak perlu mengambil tindakan apa pun.')
|
||||
->salutation('Salam hangat,' . "\n" . 'Tim Pengembang PeGas');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\View\Components;
|
||||
|
||||
use Illuminate\View\Component;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AppLayout extends Component
|
||||
{
|
||||
/**
|
||||
* Get the view / contents that represents the component.
|
||||
*/
|
||||
public function render(): View
|
||||
{
|
||||
return view('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\View\Components;
|
||||
|
||||
use Illuminate\View\Component;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class GuestLayout extends Component
|
||||
{
|
||||
/**
|
||||
* Get the view / contents that represents the component.
|
||||
*/
|
||||
public function render(): View
|
||||
{
|
||||
return view('layouts.guest');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
use Illuminate\Foundation\Application;
|
||||
use Symfony\Component\Console\Input\ArgvInput;
|
||||
|
||||
define('LARAVEL_START', microtime(true));
|
||||
|
||||
// Register the Composer autoloader...
|
||||
require __DIR__.'/vendor/autoload.php';
|
||||
|
||||
// Bootstrap Laravel and handle the command...
|
||||
/** @var Application $app */
|
||||
$app = require_once __DIR__.'/bootstrap/app.php';
|
||||
|
||||
$status = $app->handleCommand(new ArgvInput);
|
||||
|
||||
exit($status);
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
|
||||
return Application::configure(basePath: dirname(__DIR__))
|
||||
->withRouting(
|
||||
web: __DIR__.'/../routes/web.php',
|
||||
commands: __DIR__.'/../routes/console.php',
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
//
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
//
|
||||
})->create();
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
*
|
||||
!.gitignore
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
App\Providers\AppServiceProvider::class,
|
||||
];
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
{
|
||||
"$schema": "https://getcomposer.org/schema.json",
|
||||
"name": "laravel/laravel",
|
||||
"type": "project",
|
||||
"description": "The skeleton application for the Laravel framework.",
|
||||
"keywords": ["laravel", "framework"],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": "^8.2",
|
||||
"doctrine/dbal": "^4.4",
|
||||
"laravel/framework": "^12.0",
|
||||
"laravel/tinker": "^2.10.1",
|
||||
"maatwebsite/excel": "^3.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.23",
|
||||
"laravel/breeze": "^2.4",
|
||||
"laravel/pail": "^1.2.2",
|
||||
"laravel/pint": "^1.13",
|
||||
"laravel/sail": "^1.41",
|
||||
"mockery/mockery": "^1.6",
|
||||
"nunomaduro/collision": "^8.6",
|
||||
"phpunit/phpunit": "^11.5.3"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"App\\": "app/",
|
||||
"Database\\Factories\\": "database/factories/",
|
||||
"Database\\Seeders\\": "database/seeders/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"post-autoload-dump": [
|
||||
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
|
||||
"@php artisan package:discover --ansi"
|
||||
],
|
||||
"post-update-cmd": [
|
||||
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
|
||||
],
|
||||
"post-root-package-install": [
|
||||
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
|
||||
],
|
||||
"post-create-project-cmd": [
|
||||
"@php artisan key:generate --ansi",
|
||||
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
|
||||
"@php artisan migrate --graceful --ansi"
|
||||
],
|
||||
"dev": [
|
||||
"Composer\\Config::disableProcessTimeout",
|
||||
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite"
|
||||
],
|
||||
"test": [
|
||||
"@php artisan config:clear --ansi",
|
||||
"@php artisan test"
|
||||
]
|
||||
},
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"dont-discover": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"optimize-autoloader": true,
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true,
|
||||
"allow-plugins": {
|
||||
"pestphp/pest-plugin": true,
|
||||
"php-http/discovery": true
|
||||
}
|
||||
},
|
||||
"minimum-stability": "stable",
|
||||
"prefer-stable": true
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,126 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value is the name of your application, which will be used when the
|
||||
| framework needs to place the application's name in a notification or
|
||||
| other UI elements where an application name needs to be displayed.
|
||||
|
|
||||
*/
|
||||
|
||||
'name' => env('APP_NAME', 'PeGas'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Environment
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value determines the "environment" your application is currently
|
||||
| running in. This may determine how you prefer to configure various
|
||||
| services the application utilizes. Set this in your ".env" file.
|
||||
|
|
||||
*/
|
||||
|
||||
'env' => env('APP_ENV', 'production'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Debug Mode
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When your application is in debug mode, detailed error messages with
|
||||
| stack traces will be shown on every error that occurs within your
|
||||
| application. If disabled, a simple generic error page is shown.
|
||||
|
|
||||
*/
|
||||
|
||||
'debug' => (bool) env('APP_DEBUG', false),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application URL
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This URL is used by the console to properly generate URLs when using
|
||||
| the Artisan command line tool. You should set this to the root of
|
||||
| the application so that it's available within Artisan commands.
|
||||
|
|
||||
*/
|
||||
|
||||
'url' => env('APP_URL', 'http://localhost'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Timezone
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the default timezone for your application, which
|
||||
| will be used by the PHP date and date-time functions. The timezone
|
||||
| is set to "UTC" by default as it is suitable for most use cases.
|
||||
|
|
||||
*/
|
||||
|
||||
'timezone' => env('APP_TIMEZONE', 'Asia/Jakarta'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Locale Configuration
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The application locale determines the default locale that will be used
|
||||
| by Laravel's translation / localization methods. This option can be
|
||||
| set to any locale for which you plan to have translation strings.
|
||||
|
|
||||
*/
|
||||
|
||||
'locale' => env('APP_LOCALE', 'en'),
|
||||
|
||||
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
|
||||
|
||||
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Encryption Key
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This key is utilized by Laravel's encryption services and should be set
|
||||
| to a random, 32 character string to ensure that all encrypted values
|
||||
| are secure. You should do this prior to deploying the application.
|
||||
|
|
||||
*/
|
||||
|
||||
'cipher' => 'AES-256-CBC',
|
||||
|
||||
'key' => env('APP_KEY'),
|
||||
|
||||
'previous_keys' => [
|
||||
...array_filter(
|
||||
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
|
||||
),
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Maintenance Mode Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These configuration options determine the driver used to determine and
|
||||
| manage Laravel's "maintenance mode" status. The "cache" driver will
|
||||
| allow maintenance mode to be controlled across multiple machines.
|
||||
|
|
||||
| Supported drivers: "file", "cache"
|
||||
|
|
||||
*/
|
||||
|
||||
'maintenance' => [
|
||||
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
|
||||
'store' => env('APP_MAINTENANCE_STORE', 'database'),
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Authentication Defaults
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option defines the default authentication "guard" and password
|
||||
| reset "broker" for your application. You may change these values
|
||||
| as required, but they're a perfect start for most applications.
|
||||
|
|
||||
*/
|
||||
|
||||
'defaults' => [
|
||||
'guard' => env('AUTH_GUARD', 'web'),
|
||||
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Authentication Guards
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Next, you may define every authentication guard for your application.
|
||||
| Of course, a great default configuration has been defined for you
|
||||
| which utilizes session storage plus the Eloquent user provider.
|
||||
|
|
||||
| All authentication guards have a user provider, which defines how the
|
||||
| users are actually retrieved out of your database or other storage
|
||||
| system used by the application. Typically, Eloquent is utilized.
|
||||
|
|
||||
| Supported: "session"
|
||||
|
|
||||
*/
|
||||
|
||||
'guards' => [
|
||||
'web' => [
|
||||
'driver' => 'session',
|
||||
'provider' => 'users',
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| User Providers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| All authentication guards have a user provider, which defines how the
|
||||
| users are actually retrieved out of your database or other storage
|
||||
| system used by the application. Typically, Eloquent is utilized.
|
||||
|
|
||||
| If you have multiple user tables or models you may configure multiple
|
||||
| providers to represent the model / table. These providers may then
|
||||
| be assigned to any extra authentication guards you have defined.
|
||||
|
|
||||
| Supported: "database", "eloquent"
|
||||
|
|
||||
*/
|
||||
|
||||
'providers' => [
|
||||
'users' => [
|
||||
'driver' => 'eloquent',
|
||||
'model' => env('AUTH_MODEL', App\Models\User::class),
|
||||
],
|
||||
|
||||
// 'users' => [
|
||||
// 'driver' => 'database',
|
||||
// 'table' => 'users',
|
||||
// ],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Resetting Passwords
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These configuration options specify the behavior of Laravel's password
|
||||
| reset functionality, including the table utilized for token storage
|
||||
| and the user provider that is invoked to actually retrieve users.
|
||||
|
|
||||
| The expiry time is the number of minutes that each reset token will be
|
||||
| considered valid. This security feature keeps tokens short-lived so
|
||||
| they have less time to be guessed. You may change this as needed.
|
||||
|
|
||||
| The throttle setting is the number of seconds a user must wait before
|
||||
| generating more password reset tokens. This prevents the user from
|
||||
| quickly generating a very large amount of password reset tokens.
|
||||
|
|
||||
*/
|
||||
|
||||
'passwords' => [
|
||||
'users' => [
|
||||
'provider' => 'users',
|
||||
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
|
||||
'expire' => 60,
|
||||
'throttle' => 60,
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Password Confirmation Timeout
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may define the number of seconds before a password confirmation
|
||||
| window expires and users are asked to re-enter their password via the
|
||||
| confirmation screen. By default, the timeout lasts for three hours.
|
||||
|
|
||||
*/
|
||||
|
||||
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Cache Store
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default cache store that will be used by the
|
||||
| framework. This connection is utilized if another isn't explicitly
|
||||
| specified when running a cache operation inside the application.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('CACHE_STORE', 'database'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cache Stores
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may define all of the cache "stores" for your application as
|
||||
| well as their drivers. You may even define multiple stores for the
|
||||
| same cache driver to group types of items stored in your caches.
|
||||
|
|
||||
| Supported drivers: "array", "database", "file", "memcached",
|
||||
| "redis", "dynamodb", "octane", "null"
|
||||
|
|
||||
*/
|
||||
|
||||
'stores' => [
|
||||
|
||||
'array' => [
|
||||
'driver' => 'array',
|
||||
'serialize' => false,
|
||||
],
|
||||
|
||||
'database' => [
|
||||
'driver' => 'database',
|
||||
'connection' => env('DB_CACHE_CONNECTION'),
|
||||
'table' => env('DB_CACHE_TABLE', 'cache'),
|
||||
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
|
||||
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
|
||||
],
|
||||
|
||||
'file' => [
|
||||
'driver' => 'file',
|
||||
'path' => storage_path('framework/cache/data'),
|
||||
'lock_path' => storage_path('framework/cache/data'),
|
||||
],
|
||||
|
||||
'memcached' => [
|
||||
'driver' => 'memcached',
|
||||
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
|
||||
'sasl' => [
|
||||
env('MEMCACHED_USERNAME'),
|
||||
env('MEMCACHED_PASSWORD'),
|
||||
],
|
||||
'options' => [
|
||||
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
|
||||
],
|
||||
'servers' => [
|
||||
[
|
||||
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
|
||||
'port' => env('MEMCACHED_PORT', 11211),
|
||||
'weight' => 100,
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
'redis' => [
|
||||
'driver' => 'redis',
|
||||
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
|
||||
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
|
||||
],
|
||||
|
||||
'dynamodb' => [
|
||||
'driver' => 'dynamodb',
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
|
||||
'endpoint' => env('DYNAMODB_ENDPOINT'),
|
||||
],
|
||||
|
||||
'octane' => [
|
||||
'driver' => 'octane',
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cache Key Prefix
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
|
||||
| stores, there might be other applications using the same cache. For
|
||||
| that reason, you may prefix every cache key to avoid collisions.
|
||||
|
|
||||
*/
|
||||
|
||||
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Database Connection Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify which of the database connections below you wish
|
||||
| to use as your default connection for database operations. This is
|
||||
| the connection which will be utilized unless another connection
|
||||
| is explicitly specified when you execute a query / statement.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('DB_CONNECTION', 'sqlite'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Database Connections
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Below are all of the database connections defined for your application.
|
||||
| An example configuration is provided for each database system which
|
||||
| is supported by Laravel. You're free to add / remove connections.
|
||||
|
|
||||
*/
|
||||
|
||||
'connections' => [
|
||||
|
||||
'sqlite' => [
|
||||
'driver' => 'sqlite',
|
||||
'url' => env('DB_URL'),
|
||||
'database' => env('DB_DATABASE', database_path('database.sqlite')),
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
|
||||
'busy_timeout' => null,
|
||||
'journal_mode' => null,
|
||||
'synchronous' => null,
|
||||
],
|
||||
|
||||
'mysql' => [
|
||||
'driver' => 'mysql',
|
||||
'url' => env('DB_URL'),
|
||||
'host' => env('DB_HOST', '127.0.0.1'),
|
||||
'port' => env('DB_PORT', '3306'),
|
||||
'database' => env('DB_DATABASE', 'laravel'),
|
||||
'username' => env('DB_USERNAME', 'root'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'unix_socket' => env('DB_SOCKET', ''),
|
||||
'charset' => env('DB_CHARSET', 'utf8mb4'),
|
||||
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
'strict' => true,
|
||||
'engine' => null,
|
||||
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||
]) : [],
|
||||
],
|
||||
|
||||
'mariadb' => [
|
||||
'driver' => 'mariadb',
|
||||
'url' => env('DB_URL'),
|
||||
'host' => env('DB_HOST', '127.0.0.1'),
|
||||
'port' => env('DB_PORT', '3306'),
|
||||
'database' => env('DB_DATABASE', 'laravel'),
|
||||
'username' => env('DB_USERNAME', 'root'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'unix_socket' => env('DB_SOCKET', ''),
|
||||
'charset' => env('DB_CHARSET', 'utf8mb4'),
|
||||
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
'strict' => true,
|
||||
'engine' => null,
|
||||
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||
]) : [],
|
||||
],
|
||||
|
||||
'pgsql' => [
|
||||
'driver' => 'pgsql',
|
||||
'url' => env('DB_URL'),
|
||||
'host' => env('DB_HOST', '127.0.0.1'),
|
||||
'port' => env('DB_PORT', '5432'),
|
||||
'database' => env('DB_DATABASE', 'laravel'),
|
||||
'username' => env('DB_USERNAME', 'root'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'charset' => env('DB_CHARSET', 'utf8'),
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
'search_path' => 'public',
|
||||
'sslmode' => 'prefer',
|
||||
],
|
||||
|
||||
'sqlsrv' => [
|
||||
'driver' => 'sqlsrv',
|
||||
'url' => env('DB_URL'),
|
||||
'host' => env('DB_HOST', 'localhost'),
|
||||
'port' => env('DB_PORT', '1433'),
|
||||
'database' => env('DB_DATABASE', 'laravel'),
|
||||
'username' => env('DB_USERNAME', 'root'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'charset' => env('DB_CHARSET', 'utf8'),
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
|
||||
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Migration Repository Table
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This table keeps track of all the migrations that have already run for
|
||||
| your application. Using this information, we can determine which of
|
||||
| the migrations on disk haven't actually been run on the database.
|
||||
|
|
||||
*/
|
||||
|
||||
'migrations' => [
|
||||
'table' => 'migrations',
|
||||
'update_date_on_publish' => true,
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Redis Databases
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Redis is an open source, fast, and advanced key-value store that also
|
||||
| provides a richer body of commands than a typical key-value system
|
||||
| such as Memcached. You may define your connection settings here.
|
||||
|
|
||||
*/
|
||||
|
||||
'redis' => [
|
||||
|
||||
'client' => env('REDIS_CLIENT', 'phpredis'),
|
||||
|
||||
'options' => [
|
||||
'cluster' => env('REDIS_CLUSTER', 'redis'),
|
||||
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
|
||||
'persistent' => env('REDIS_PERSISTENT', false),
|
||||
],
|
||||
|
||||
'default' => [
|
||||
'url' => env('REDIS_URL'),
|
||||
'host' => env('REDIS_HOST', '127.0.0.1'),
|
||||
'username' => env('REDIS_USERNAME'),
|
||||
'password' => env('REDIS_PASSWORD'),
|
||||
'port' => env('REDIS_PORT', '6379'),
|
||||
'database' => env('REDIS_DB', '0'),
|
||||
],
|
||||
|
||||
'cache' => [
|
||||
'url' => env('REDIS_URL'),
|
||||
'host' => env('REDIS_HOST', '127.0.0.1'),
|
||||
'username' => env('REDIS_USERNAME'),
|
||||
'password' => env('REDIS_PASSWORD'),
|
||||
'port' => env('REDIS_PORT', '6379'),
|
||||
'database' => env('REDIS_CACHE_DB', '1'),
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Filesystem Disk
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the default filesystem disk that should be used
|
||||
| by the framework. The "local" disk, as well as a variety of cloud
|
||||
| based disks are available to your application for file storage.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('FILESYSTEM_DISK', 'local'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Filesystem Disks
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Below you may configure as many filesystem disks as necessary, and you
|
||||
| may even configure multiple disks for the same driver. Examples for
|
||||
| most supported storage drivers are configured here for reference.
|
||||
|
|
||||
| Supported drivers: "local", "ftp", "sftp", "s3"
|
||||
|
|
||||
*/
|
||||
|
||||
'disks' => [
|
||||
|
||||
'local' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app/private'),
|
||||
'serve' => true,
|
||||
'throw' => false,
|
||||
'report' => false,
|
||||
],
|
||||
|
||||
'public' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app/public'),
|
||||
'url' => env('APP_URL').'/storage',
|
||||
'visibility' => 'public',
|
||||
'throw' => false,
|
||||
'report' => false,
|
||||
],
|
||||
|
||||
's3' => [
|
||||
'driver' => 's3',
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'region' => env('AWS_DEFAULT_REGION'),
|
||||
'bucket' => env('AWS_BUCKET'),
|
||||
'url' => env('AWS_URL'),
|
||||
'endpoint' => env('AWS_ENDPOINT'),
|
||||
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
|
||||
'throw' => false,
|
||||
'report' => false,
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Symbolic Links
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure the symbolic links that will be created when the
|
||||
| `storage:link` Artisan command is executed. The array keys should be
|
||||
| the locations of the links and the values should be their targets.
|
||||
|
|
||||
*/
|
||||
|
||||
'links' => [
|
||||
public_path('storage') => storage_path('app/public'),
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
<?php
|
||||
|
||||
use Monolog\Handler\NullHandler;
|
||||
use Monolog\Handler\StreamHandler;
|
||||
use Monolog\Handler\SyslogUdpHandler;
|
||||
use Monolog\Processor\PsrLogMessageProcessor;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Log Channel
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option defines the default log channel that is utilized to write
|
||||
| messages to your logs. The value provided here should match one of
|
||||
| the channels present in the list of "channels" configured below.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('LOG_CHANNEL', 'stack'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Deprecations Log Channel
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the log channel that should be used to log warnings
|
||||
| regarding deprecated PHP and library features. This allows you to get
|
||||
| your application ready for upcoming major versions of dependencies.
|
||||
|
|
||||
*/
|
||||
|
||||
'deprecations' => [
|
||||
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
|
||||
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Log Channels
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure the log channels for your application. Laravel
|
||||
| utilizes the Monolog PHP logging library, which includes a variety
|
||||
| of powerful log handlers and formatters that you're free to use.
|
||||
|
|
||||
| Available drivers: "single", "daily", "slack", "syslog",
|
||||
| "errorlog", "monolog", "custom", "stack"
|
||||
|
|
||||
*/
|
||||
|
||||
'channels' => [
|
||||
|
||||
'stack' => [
|
||||
'driver' => 'stack',
|
||||
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
|
||||
'ignore_exceptions' => false,
|
||||
],
|
||||
|
||||
'single' => [
|
||||
'driver' => 'single',
|
||||
'path' => storage_path('logs/laravel.log'),
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'daily' => [
|
||||
'driver' => 'daily',
|
||||
'path' => storage_path('logs/laravel.log'),
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'days' => env('LOG_DAILY_DAYS', 14),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'slack' => [
|
||||
'driver' => 'slack',
|
||||
'url' => env('LOG_SLACK_WEBHOOK_URL'),
|
||||
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
|
||||
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
|
||||
'level' => env('LOG_LEVEL', 'critical'),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'papertrail' => [
|
||||
'driver' => 'monolog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
|
||||
'handler_with' => [
|
||||
'host' => env('PAPERTRAIL_URL'),
|
||||
'port' => env('PAPERTRAIL_PORT'),
|
||||
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
|
||||
],
|
||||
'processors' => [PsrLogMessageProcessor::class],
|
||||
],
|
||||
|
||||
'stderr' => [
|
||||
'driver' => 'monolog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'handler' => StreamHandler::class,
|
||||
'handler_with' => [
|
||||
'stream' => 'php://stderr',
|
||||
],
|
||||
'formatter' => env('LOG_STDERR_FORMATTER'),
|
||||
'processors' => [PsrLogMessageProcessor::class],
|
||||
],
|
||||
|
||||
'syslog' => [
|
||||
'driver' => 'syslog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'errorlog' => [
|
||||
'driver' => 'errorlog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'null' => [
|
||||
'driver' => 'monolog',
|
||||
'handler' => NullHandler::class,
|
||||
],
|
||||
|
||||
'emergency' => [
|
||||
'path' => storage_path('logs/laravel.log'),
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Mailer
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default mailer that is used to send all email
|
||||
| messages unless another mailer is explicitly specified when sending
|
||||
| the message. All additional mailers can be configured within the
|
||||
| "mailers" array. Examples of each type of mailer are provided.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('MAIL_MAILER', 'log'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Mailer Configurations
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure all of the mailers used by your application plus
|
||||
| their respective settings. Several examples have been configured for
|
||||
| you and you are free to add your own as your application requires.
|
||||
|
|
||||
| Laravel supports a variety of mail "transport" drivers that can be used
|
||||
| when delivering an email. You may specify which one you're using for
|
||||
| your mailers below. You may also add additional mailers if needed.
|
||||
|
|
||||
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
|
||||
| "postmark", "resend", "log", "array",
|
||||
| "failover", "roundrobin"
|
||||
|
|
||||
*/
|
||||
|
||||
'mailers' => [
|
||||
|
||||
'smtp' => [
|
||||
'transport' => 'smtp',
|
||||
'scheme' => env('MAIL_SCHEME'),
|
||||
'url' => env('MAIL_URL'),
|
||||
'host' => env('MAIL_HOST', '127.0.0.1'),
|
||||
'port' => env('MAIL_PORT', 2525),
|
||||
'username' => env('MAIL_USERNAME'),
|
||||
'password' => env('MAIL_PASSWORD'),
|
||||
'timeout' => null,
|
||||
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
|
||||
],
|
||||
|
||||
'ses' => [
|
||||
'transport' => 'ses',
|
||||
],
|
||||
|
||||
'postmark' => [
|
||||
'transport' => 'postmark',
|
||||
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
|
||||
// 'client' => [
|
||||
// 'timeout' => 5,
|
||||
// ],
|
||||
],
|
||||
|
||||
'resend' => [
|
||||
'transport' => 'resend',
|
||||
],
|
||||
|
||||
'sendmail' => [
|
||||
'transport' => 'sendmail',
|
||||
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
|
||||
],
|
||||
|
||||
'log' => [
|
||||
'transport' => 'log',
|
||||
'channel' => env('MAIL_LOG_CHANNEL'),
|
||||
],
|
||||
|
||||
'array' => [
|
||||
'transport' => 'array',
|
||||
],
|
||||
|
||||
'failover' => [
|
||||
'transport' => 'failover',
|
||||
'mailers' => [
|
||||
'smtp',
|
||||
'log',
|
||||
],
|
||||
'retry_after' => 60,
|
||||
],
|
||||
|
||||
'roundrobin' => [
|
||||
'transport' => 'roundrobin',
|
||||
'mailers' => [
|
||||
'ses',
|
||||
'postmark',
|
||||
],
|
||||
'retry_after' => 60,
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Global "From" Address
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| You may wish for all emails sent by your application to be sent from
|
||||
| the same address. Here you may specify a name and address that is
|
||||
| used globally for all emails that are sent by your application.
|
||||
|
|
||||
*/
|
||||
|
||||
'from' => [
|
||||
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
|
||||
'name' => env('MAIL_FROM_NAME', 'Example'),
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Queue Connection Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Laravel's queue supports a variety of backends via a single, unified
|
||||
| API, giving you convenient access to each backend using identical
|
||||
| syntax for each. The default queue connection is defined below.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('QUEUE_CONNECTION', 'database'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Queue Connections
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure the connection options for every queue backend
|
||||
| used by your application. An example configuration is provided for
|
||||
| each backend supported by Laravel. You're also free to add more.
|
||||
|
|
||||
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
||||
|
|
||||
*/
|
||||
|
||||
'connections' => [
|
||||
|
||||
'sync' => [
|
||||
'driver' => 'sync',
|
||||
],
|
||||
|
||||
'database' => [
|
||||
'driver' => 'database',
|
||||
'connection' => env('DB_QUEUE_CONNECTION'),
|
||||
'table' => env('DB_QUEUE_TABLE', 'jobs'),
|
||||
'queue' => env('DB_QUEUE', 'default'),
|
||||
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
'beanstalkd' => [
|
||||
'driver' => 'beanstalkd',
|
||||
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
|
||||
'queue' => env('BEANSTALKD_QUEUE', 'default'),
|
||||
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
|
||||
'block_for' => 0,
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
'sqs' => [
|
||||
'driver' => 'sqs',
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
|
||||
'queue' => env('SQS_QUEUE', 'default'),
|
||||
'suffix' => env('SQS_SUFFIX'),
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
'redis' => [
|
||||
'driver' => 'redis',
|
||||
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
|
||||
'queue' => env('REDIS_QUEUE', 'default'),
|
||||
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
|
||||
'block_for' => null,
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Job Batching
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The following options configure the database and table that store job
|
||||
| batching information. These options can be updated to any database
|
||||
| connection and table which has been defined by your application.
|
||||
|
|
||||
*/
|
||||
|
||||
'batching' => [
|
||||
'database' => env('DB_CONNECTION', 'sqlite'),
|
||||
'table' => 'job_batches',
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Failed Queue Jobs
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These options configure the behavior of failed queue job logging so you
|
||||
| can control how and where failed jobs are stored. Laravel ships with
|
||||
| support for storing failed jobs in a simple file or in a database.
|
||||
|
|
||||
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
||||
|
|
||||
*/
|
||||
|
||||
'failed' => [
|
||||
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
|
||||
'database' => env('DB_CONNECTION', 'sqlite'),
|
||||
'table' => 'failed_jobs',
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Third Party Services
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This file is for storing the credentials for third party services such
|
||||
| as Mailgun, Postmark, AWS and more. This file provides the de facto
|
||||
| location for this type of information, allowing packages to have
|
||||
| a conventional file to locate the various service credentials.
|
||||
|
|
||||
*/
|
||||
|
||||
'postmark' => [
|
||||
'token' => env('POSTMARK_TOKEN'),
|
||||
],
|
||||
|
||||
'resend' => [
|
||||
'key' => env('RESEND_KEY'),
|
||||
],
|
||||
|
||||
'ses' => [
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
],
|
||||
|
||||
'slack' => [
|
||||
'notifications' => [
|
||||
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
|
||||
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
|
||||
],
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Session Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option determines the default session driver that is utilized for
|
||||
| incoming requests. Laravel supports a variety of storage options to
|
||||
| persist session data. Database storage is a great default choice.
|
||||
|
|
||||
| Supported: "file", "cookie", "database", "memcached",
|
||||
| "redis", "dynamodb", "array"
|
||||
|
|
||||
*/
|
||||
|
||||
'driver' => env('SESSION_DRIVER', 'database'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Lifetime
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the number of minutes that you wish the session
|
||||
| to be allowed to remain idle before it expires. If you want them
|
||||
| to expire immediately when the browser is closed then you may
|
||||
| indicate that via the expire_on_close configuration option.
|
||||
|
|
||||
*/
|
||||
|
||||
'lifetime' => (int) env('SESSION_LIFETIME', 120),
|
||||
|
||||
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Encryption
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option allows you to easily specify that all of your session data
|
||||
| should be encrypted before it's stored. All encryption is performed
|
||||
| automatically by Laravel and you may use the session like normal.
|
||||
|
|
||||
*/
|
||||
|
||||
'encrypt' => env('SESSION_ENCRYPT', false),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session File Location
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When utilizing the "file" session driver, the session files are placed
|
||||
| on disk. The default storage location is defined here; however, you
|
||||
| are free to provide another location where they should be stored.
|
||||
|
|
||||
*/
|
||||
|
||||
'files' => storage_path('framework/sessions'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Database Connection
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When using the "database" or "redis" session drivers, you may specify a
|
||||
| connection that should be used to manage these sessions. This should
|
||||
| correspond to a connection in your database configuration options.
|
||||
|
|
||||
*/
|
||||
|
||||
'connection' => env('SESSION_CONNECTION'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Database Table
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When using the "database" session driver, you may specify the table to
|
||||
| be used to store sessions. Of course, a sensible default is defined
|
||||
| for you; however, you're welcome to change this to another table.
|
||||
|
|
||||
*/
|
||||
|
||||
'table' => env('SESSION_TABLE', 'sessions'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cache Store
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When using one of the framework's cache driven session backends, you may
|
||||
| define the cache store which should be used to store the session data
|
||||
| between requests. This must match one of your defined cache stores.
|
||||
|
|
||||
| Affects: "dynamodb", "memcached", "redis"
|
||||
|
|
||||
*/
|
||||
|
||||
'store' => env('SESSION_STORE'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Sweeping Lottery
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Some session drivers must manually sweep their storage location to get
|
||||
| rid of old sessions from storage. Here are the chances that it will
|
||||
| happen on a given request. By default, the odds are 2 out of 100.
|
||||
|
|
||||
*/
|
||||
|
||||
'lottery' => [2, 100],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cookie Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may change the name of the session cookie that is created by
|
||||
| the framework. Typically, you should not need to change this value
|
||||
| since doing so does not grant a meaningful security improvement.
|
||||
|
|
||||
*/
|
||||
|
||||
'cookie' => env(
|
||||
'SESSION_COOKIE',
|
||||
Str::snake((string) env('APP_NAME', 'laravel')).'_session'
|
||||
),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cookie Path
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The session cookie path determines the path for which the cookie will
|
||||
| be regarded as available. Typically, this will be the root path of
|
||||
| your application, but you're free to change this when necessary.
|
||||
|
|
||||
*/
|
||||
|
||||
'path' => env('SESSION_PATH', '/'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cookie Domain
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value determines the domain and subdomains the session cookie is
|
||||
| available to. By default, the cookie will be available to the root
|
||||
| domain and all subdomains. Typically, this shouldn't be changed.
|
||||
|
|
||||
*/
|
||||
|
||||
'domain' => env('SESSION_DOMAIN'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| HTTPS Only Cookies
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| By setting this option to true, session cookies will only be sent back
|
||||
| to the server if the browser has a HTTPS connection. This will keep
|
||||
| the cookie from being sent to you when it can't be done securely.
|
||||
|
|
||||
*/
|
||||
|
||||
'secure' => env('SESSION_SECURE_COOKIE'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| HTTP Access Only
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting this value to true will prevent JavaScript from accessing the
|
||||
| value of the cookie and the cookie will only be accessible through
|
||||
| the HTTP protocol. It's unlikely you should disable this option.
|
||||
|
|
||||
*/
|
||||
|
||||
'http_only' => env('SESSION_HTTP_ONLY', true),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Same-Site Cookies
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option determines how your cookies behave when cross-site requests
|
||||
| take place, and can be used to mitigate CSRF attacks. By default, we
|
||||
| will set this value to "lax" to permit secure cross-site requests.
|
||||
|
|
||||
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
||||
|
|
||||
| Supported: "lax", "strict", "none", null
|
||||
|
|
||||
*/
|
||||
|
||||
'same_site' => env('SESSION_SAME_SITE', 'lax'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Partitioned Cookies
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting this value to true will tie the cookie to the top-level site for
|
||||
| a cross-site context. Partitioned cookies are accepted by the browser
|
||||
| when flagged "secure" and the Same-Site attribute is set to "none".
|
||||
|
|
||||
*/
|
||||
|
||||
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1 @@
|
|||
*.sqlite*
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
|
||||
*/
|
||||
class UserFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* The current password being used by the factory.
|
||||
*/
|
||||
protected static ?string $password;
|
||||
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'name' => fake()->name(),
|
||||
'email' => fake()->unique()->safeEmail(),
|
||||
'email_verified_at' => now(),
|
||||
'password' => static::$password ??= Hash::make('password'),
|
||||
'remember_token' => Str::random(10),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the model's email address should be unverified.
|
||||
*/
|
||||
public function unverified(): static
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'email_verified_at' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->uuid('id')->primary();
|
||||
$table->string('name');
|
||||
$table->string('email')->unique();
|
||||
$table->string('nama_pangkalan')->nullable();
|
||||
$table->text('alamat')->nullable();
|
||||
$table->timestamp('email_verified_at')->nullable();
|
||||
$table->string('password');
|
||||
$table->string('role')->default('user');
|
||||
$table->rememberToken();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('password_reset_tokens', function (Blueprint $table) {
|
||||
$table->string('email')->primary();
|
||||
$table->string('token');
|
||||
$table->timestamp('created_at')->nullable();
|
||||
});
|
||||
|
||||
Schema::create('sessions', function (Blueprint $table) {
|
||||
$table->string('id')->primary();
|
||||
$table->foreignId('user_id')->nullable()->index();
|
||||
$table->string('ip_address', 45)->nullable();
|
||||
$table->text('user_agent')->nullable();
|
||||
$table->longText('payload');
|
||||
$table->integer('last_activity')->index();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('users');
|
||||
Schema::dropIfExists('password_reset_tokens');
|
||||
Schema::dropIfExists('sessions');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('faqs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('question');
|
||||
$table->text('answer');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('faqs');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('helpdesks', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('user_id', );
|
||||
$table->foreign('user_id')
|
||||
->references('id')
|
||||
->on('users')
|
||||
->onDelete('cascade');
|
||||
|
||||
$table->text('message');
|
||||
$table->string('attachment')->nullable();
|
||||
$table->text('reply')->nullable();
|
||||
$table->enum('status', ['pending', 'answered'])->default('pending');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('helpdesks');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('artikels', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('judul');
|
||||
$table->string('gambar');
|
||||
$table->text('deskripsi');
|
||||
$table->string('sumber');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('artikels');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('helpdesks', function (Blueprint $table) {
|
||||
$table->string('user_id')->change();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('helpdesks', function (Blueprint $table) {
|
||||
$table->integer('user_id')->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue