commit 22356f630e524f1816786f3e18740d4b0a97f06b Author: Onie Date: Thu Jul 23 22:12:32 2026 +0700 chore: initial commit Dutra Store POS app diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9373a56 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Secrets / config (Supabase keys) +lib/config.dart +supabse.txt + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.kilo/agent/uiux-pos-grosir.md b/.kilo/agent/uiux-pos-grosir.md new file mode 100644 index 0000000..b61b5ae --- /dev/null +++ b/.kilo/agent/uiux-pos-grosir.md @@ -0,0 +1,195 @@ +# UI/UX Design Skill — Dutra Store (POS Grosir Flutter) + +Gunakan skill ini sebagai acuan setiap kali mengubah, menambah, atau meninjau tampilan aplikasi POS grosir berbasis Flutter ini. Jika ada pertentangan, prioritaskan yang tercantum di sini. + +## 1. Tujuan Utama +- Transaksi cepat tanpa hambatan visual. +- Tidak ada overflow/keluar layar di ukuran HP kecil. +- Status stok, harga, dan aksi utama terlihat jelas dalam 1 scan. +- Maintain konsistensi visual antar screen. + +## 2. Design System + +### 2.1 Tema +- Theme gelap (dark) sebagai basis utama. +- Warna aksen: amber (`Colors.amber`). +- Radius default: 18 untuk kartu, 12 untuk input/dialog, 8 untuk chip/tag. +- Font: gunakan `Theme.of(context).textTheme` agar sesuai pengaturan sistem. + +### 2.2 Warna Semantik +- `kAccent` — amber untuk aksen dan highlight. +- `kSuccess` — hijau untuk status lunas/berhasil. +- `kDanger` — merah untuk pembatalan/error/stok habis. +- `kMuted` — abu-abu untuk teks sekunder/timestamp. +- `kSurface2` — background chip yang tidak aktif. +- `kBorder` — border untuk chip dan outline. + +### 2.3 Spacing & Layout +- Gunakan `EdgeInsets` tetap untuk konsistensi: + - `EdgeInsets.all(12)` padding screen/list. + - `EdgeInsets.all(16)` padding form/dialog. + - `EdgeInsets.symmetric(horizontal: 14, vertical: 10)` untuk baris list. +- Gap antar field/form: `SizedBox(height: 10)`. +- Gap antar section: `SizedBox(height: 14)`. + +### 2.4 Kartu (Card) +- Semua item list/kartu harus punya padding minimal `EdgeInsets.all(12)`. +- Jangan hardcode tinggi kartu; gunakan `Column` + `MainAxisSize.min` atau `IntrinsicHeight` bila perlu. +- Jika ada 3+ field di dalam kartu, prioritaskan wrap/scroll. +- Status transaksi harus jelas: + - Lunas: badge/icon hijau. + - Belum lunas: badge/icon amber/oranye. + - Dibatalkan: badge/icon merah + `TextDecoration.lineThrough`. + +### 2.5 Input & Form +- Label jelas, helper text opsional untuk field opsional. +- Jangan taruh form di dalam `Column` tanpa `SingleChildScrollView` jika total tinggi form bisa melebihi layar. +- Saat keyboard muncul, pastikan field terlihat: + - Bungkus form dengan `SingleChildScrollView` + `padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom)`. + +### 2.6 Tombol & Aksi +- Primary action (Bayar, Tambah, Simpan): `FilledButton` berwarna aksen. +- Destructive action (Hapus, Batalkan): `FilledButton` / `OutlinedButton` berwarna merah (`kDanger`). +- Secondary action (Batal, Tutup): `TextButton` atau `OutlinedButton`. +- Setiap dialog harus punya urutan aksi: **Konfirmasi** di kanan/bawah, **Batal** di kiri/atas. + +### 2.6a Haptic & Feedback +- Aksi signifikan yang cepat: tambah item ke keranjang, print struk, scan barcode → `HapticFeedback.lightImpact()`. +- Aksi destruktif atau butuh konfirmasi: hapus item/batal transaksi → `HapticFeedback.mediumImpact()`. +- Sukses transaksi/tampilkan feedback →lanjut ke `SnackBar` hijau (`kSuccess`), jangan pakai dialog sukses untuk hal yang cepat. +- Jangan paksa haptic di setiap tap; hanya untuk aksi yang jelas berdampak. + +### 2.7 Auto-Scroll & Keyboard Behavior +- Setiap form di dalam bottom sheet atau dialog harus meng-handle keyboard muncul/tutup. +- Gunakan `MediaQuery.of(context).viewInsets.bottom` untuk padding bawah dinamis pada `SingleChildScrollView`. +- Untuk bottom sheet form yang tinggi dan perlu auto-expand: + 1. Pakai `DraggableScrollableController`. + 2. Buat `FocusNode` untuk setiap `TextField`. + 3. Tambah listener ke setiap focus node: jika `hasFocus`, animasikan sheet ke `maxChildSize` (misal `0.92`), lalu panggil `Scrollable.ensureVisible()` agar field aktif terlihat. + 4. Durasi animasi sheet: `300ms`, scroll: `250ms`, alignment: `0.0`. +- Jangan andal `Scaffold.resizeToAvoidBottomInset` saja untuk bottom sheet form kompleks; manual padding lebih stabil untuk kasus form panjang. + +### 2.8 Empty State +- Jangan tampilkan teks kosong tanpa visual indicator. +- Minimal: icon + teks. Contoh: `Icon(Icons.shopping_cart_outlined, size: 48, color: kMuted)` + teks "Keranjang kosong". +- Center alignment, `Column` dengan `MainAxisSize.min`. +- Konsisten pakai ikon `outlined` variant untuk empty state. + +### 2.9 Dialog Button Layout +- Mobile: tombol dialog harus **full-width stacked vertikal** dengan `SizedBox(height: 8)` antar tombol. +- Urutan: **Batal** di atas, **Konfirmasi** di bawah. +- Jangan pakai `Row` untuk 2 tombol di dialog mobile, kecuali screen width > 600dp. +- Tombol konfirmasi destruktif: `FilledButton` dengan `backgroundColor: kDanger`. +- Tombol konfirmasi positif: `FilledButton` dengan `backgroundColor: kAccent` atau `kSuccess`. + +### 2.10 Loading State +- Untuk operasi < 500ms: tidak perlu loading indicator. +- Untuk operasi > 500ms: tampilkan loading di button yang dipencet. + - Spinner: `CircularProgressIndicator(strokeWidth: 2, color: Color(0xFF06210F))` untuk light button text. + - Spinner: `CircularProgressIndicator(strokeWidth: 2, color: kAccent)` untuk dark button text. +- Untuk full-screen loading: gunakan `CircularProgressIndicator(color: kAccent)` di `Center`. +- Jangan gunakan `LinearProgressIndicator` kecuali untuk determinate progress yang jelas. +- Jika list kosong dan pengguna bisa melakukan aksi (misal tambah produk), tampilkan `FloatingActionButton` atau `FilledButton` sebagai helper agar tidak dead-end. + +### 2.11 Error State +- Error dari form validation: tampilkan inline di bawah field, warna `kDanger`, font 13. +- Error dari operasi database/API: tampilkan `SnackBar` merah (`kDanger`). +- Jangan hanya pakai warna tanpa label. Tambahkan ikon/prefix jika perlu. +- Jika field error, pastikan `TextField` tetap bisa di-focus dan di-scroll. + +## 3. Responsif & Overflow + +### 3.1 Grid Produk (Kasir) +- Default: 2 kolom di layar HP (`crossAxisCount: 2`). +- Tablet (lebar > 600dp): naik jadi 3 kolom. +- Jangan pakai `childAspectRatio` tetap yang bikin kartu terlalu tinggi/pendek. Gunakan `AspectRatio(1.1)` atau biarkan `GridView` yang menentukan tinggi. + +### 3.2 Payment Method Chips +- Urutan chip di UI: **Tunai**, **Bank**, **QRIS**, **Bayar Nanti**, **Split**. +- Untuk mobile, kelompokkan menjadi: + - Baris atas: 3 chip (`Tunai`, `Bank`, `QRIS`) dalam satu `Row` dengan `Expanded`. + - Divider tipis antar kelompok. + - Baris bawah: 2 chip (`Bayar Nanti`, `Split`) dalam satu `Row` dengan `Expanded`. +- Jangan pakai `Wrap` untuk payment chips. `Wrap` boleh dipakai kembali untuk kasus lain seperti `Filter chips` atau `Tag`. +- Chip harus compact, aman di layar kecil, dan tidak memaksa scroll horizontal. + +### 3.3 Bottom Sheet +- Keranjang harus berupa bottom sheet, bukan panel tetap. +- Sheet harus bisa di-drag (`DraggableScrollableSheet` atau `showModalBottomSheet` dengan `isScrollControlled: true`). +- Konten sheet harus **selalu scrollable** (`SingleChildScrollView`), tanpa `Expanded` di dalamnya, agar footer tidak pernah terhalangi keyboard. +- Untuk menutup sheet dari aksi di dalamnya, gunakan `Navigator.pop(sheetContext)` bukan `parentContext`. + +### 3.4 Dialog +- Semua dialog input yang panjang harus dibungkus `SingleChildScrollView` atau `SingleChildScrollView` di dalam `AlertDialog` agar bisa di-scroll saat keyboard muncul. +- Jangan pakai `Expanded` di dalam dialog yang berpotensi overflow. + +### 3.5 Produk & Form Panjang +- Tab Produk adalah gabungan form + list produk. Gunakan `SingleChildScrollView` + `ListView.builder` dengan `shrinkWrap: true` agar form bisa di-scroll tanpa overflow. + +### 3.6 Teks +- Jangan hardcode font size. Gunakan skema `TextStyle` dari `ThemeData`. +- Jika label teks bisa panjang (mis. nama produk), batasi maksimal 2 baris dengan `maxLines: 2` + `overflow: TextOverflow.ellipsis`. +- ID transaksi/nama panjang: `Expanded` + `TextOverflow.ellipsis` agar tidak overflow di `Row`. + +## 4. UX untuk Kasir (Critical Path) +- Target: transaksi selesai dalam 3 tap (pilih produk → bayar → selesai). +- Jangan sembunyikan aksi utama (Bayar) di bawah banyak opsi. +- Tampilkan total, diskon, dan kembalian secara **real-time**. +- Gunakan chip/segmented button untuk tipe pembeli (Umum/Reseller) — jangan dropdown. +- Setiap item di keranjang harus bisa diubah qty atau tipe harga dalam 1 tap. +- Jika stok habis, matikan visual (opacity turun, disable tap) dan tampilkan badge "Habis". +- Jika stok menipis, tampilkan badge peringatan oranye sebelum habis. + +## 5. Payment Flow: Bayar Nanti +- Saat checkout pilih **Bayar Nanti**, tombol harus jelas: **"Pesanan Sekarang"**. +- Field "Uang Dibayar" menjadi disabled dengan label **"Belum Bayar"**. +- Tampilkan status **"Belum Bayar"** di receipt/summary dengan warna `kMuted`. +- Di Riwayat, transaksi unpaid harus punya badge/status yang menonjol. +- Saat customer datang bayar: tombol **"Terima Pembayaran"** atau **"Bayar Sisa"** di detail transaksi. + +## 6. Aksesibilitas & Feedback +- Minimal tap target: 44x44dp untuk semua tombol/icon. +- Warna teks harus kontras dengan background (minimal 4.5:1 untuk teks normal). +- Jangan hanya andal warna untuk status (tambah ikon/label). Contoh: stok habis = badge merah + teks "Habis". +- Setiap aksi berhasil/gagal harus ada `SnackBar` feedback: + - Sukses: hijau (`kSuccess`). + - Error: merah (`kDanger`). + - Info: biru/abu. +- Loading state harus muncul saat operasi > 500ms. Gunakan `CircularProgressIndicator(color: kAccent)`. + +## 7. Role-Based Visibility +- Fitur yang tidak diizinkan untuk role tertentu harus **disembunyikan sepenuhnya**, bukan cuma di-disable. +- Admin: lihat semua transaksi + filter tanggal + aksi batalkan transaksi. +- Kasir: lihat transaksi hari ini, tidak ada aksi batalkan, tidak ada filter tanggal. + +## 8. List & Pagination +- Gunakan `ListView.separated` dengan `itemCount` yang sesuai untuk performa. +- Tombol "Muat lebih banyak" harus ada di bawah list jika data bisa banyak. +- Filter chips: gunakan `Wrap` agar responsif di layar kecil. + +## 8a. Printer & Thermal Receipt +- Semua teks struk harus Bahasa Indonesia dan ringkas. +- Struk wajib menampilkan: nama toko, tanggal, jam, nomor transaksi, daftar item, diskon (jika ada), total, metode pembayaran, detail pembayaran tunai/split (jika ada), dan **nama kasir**. +- Jangan tampilkan label per-item **Umum/Reseller** di struk thermal, agar lebih rapi. +- Jika `splitPayment` ada, tampilkan per bagian: `Split Tunai`, `Split Bank`, atau `Split QRIS` beserta nominalnya. +- Batasi lebar konten sesuai PaperSize.mm58 agar tidak terpotong. +- Setelah cetak, arahkan feedback ke user melalui `SnackBar`, bukan hanya log. +- Flow pairing printer harus bisa diakses oleh role kasir, bukan hanya admin. + +## 9. Reusability +- Buat widget kecil reuseable untuk komponen yang berulang: `_Tag`, `_ReportCard`, `_Avatar`, `_Stepper`, `_PaymentMethodChip`. +- Jangan duplikasi warna/spacing. Taruh konstanta di `lib/utils/colors.dart`. + +## 10. Checklist Sebelum Submit Perubahan UI/UX +- [ ] `flutter analyze` → No issues found (tanpa error). +- [ ] Coba di layar kecil (HP 5") dan besar (tablet). +- [ ] Coba dengan keyboard muncul (input uang/diskon). +- [ ] Coba mode gelap dan terang (jika supported). +- [ ] Pastikan tidak ada hardcoded height yang bikin overflow. +- [ ] Semua teks dalam Bahasa Indonesia. +- [ ] Konsisten pakai `formatRupiah()` untuk angka mata uang. + +## 11. Referensi Project +- `lib/utils/colors.dart` — design tokens. +- `lib/screens/kasir_screen.dart` — contoh bottom sheet cart, grid produk, dialog pembayaran. +- `lib/screens/riwayat_screen.dart` — contoh kartu laporan, filter role-based. diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..70a7d44 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "9f455d2486bcb28cad87b062475f42edc959f636" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + - platform: android + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + - platform: ios + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + - platform: linux + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + - platform: macos + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + - platform: web + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + - platform: windows + create_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + base_revision: 9f455d2486bcb28cad87b062475f42edc959f636 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/PRD.md b/PRD.md new file mode 100644 index 0000000..6b37988 --- /dev/null +++ b/PRD.md @@ -0,0 +1,476 @@ +# PRD - Dutra Store + +## Changelog + +### v1.0.1 — 2026-07-22 +- Perbaikan UI/UX form produk: auto-scroll keyboard pada Tambah Produk dan Edit Produk. +- reorganisasi metode pembayaran: kelompok atas 3 (Tunai, Bank, QRIS), kelompok bawah 2 (Bayar Nanti, Split). +- Validasi harga reseller: harga reseller tidak boleh lebih tinggi dari harga umum. +- Fix sinttas `produk_screen.dart` dan `kasir_screen.dart` (`flutter analyze` clean dari error). +- Deploy release APK ke device: **TECNO KM4** (Android 15). + +### v1.0.0 — 2026-07-20 (Resmikan) +- Fitur lengkap: Auth, Kasir, Produk, Riwayat, Pembayaran, Struk, Printer Bluetooth, Export PDF. +- Release APK pertama untuk distribusi. + +## 1. Ringkasan Produk +Dutra Store adalah aplikasi kasir digital berbasis Flutter untuk toko grosir. Aplikasi ini menghubungkan multi-device melalui sinkronisasi realtime Supabase, sehingga data produk dan transaksi dapat diakses dari berbagai perangkat secara bersamaan. + +## 2. Tujuan Bisnis +- Mempercepat transaksi penjualan di toko grosir. +- Menjamin harga konsisten untuk pelanggan umum dan reseller. +- Menyediakan laporan penjualan yang realtime. +- Mengurangi risiko inkonsistensi data antar perangkat kasir. +- Memisahkan wewenang antara admin (pemilik) dan kasir (karyawan). + +## 3. Target Pengguna +- **Admin** (pemilik toko): mengelola produk, melihat laporan, mengubah setting toko. +- **Kasir** (karyawan): melakukan transaksi penjualan, tidak bisa mengubah data master. +- Pelanggan reseller yang mendapatkan harga khusus. + +## 4. Lingkung Aplikasi +- Platform: Android (emulator & perangkat fisik). +- State management: Provider. +- Backend: Supabase (PostgreSQL). +- Autentikasi: Supabase Auth (email + password) + tabel `profiles` untuk role. +- Sinkronisasi: Realtime stream untuk `products` dan `sales` pada paid tier; pada free tier menggunakan **periodic polling 1 menit** saat app aktif sebagai fallback, ditambah pull-to-refresh manual. +- Penyimpanan lokal: `shared_preferences` untuk cache JSON + session auth dikelola oleh Supabase. +- Startup flow: `AuthGate` mengecek session/login state → `LoginScreen` atau `HomePage`. + +## 5. Role & Permission + +### 5.1 Admin +- Login ke aplikasi. +- CRUD produk (tambah, edit, hapus, atur stok & harga). +- Melihat riwayat transaksi & laporan. +- Mengelola akun kasir (tambah / nonaktifkan). +- Mengubah pengaturan toko (nama toko, mata uang, printer default). + +### 5.2 Kasir +- Login ke aplikasi. +- Melakukan transaksi penjualan (tab Kasir). +- Tidak dapat mengedit atau menghapus produk. +- Tidak dapat melihat laporan lengkap / riwayat lama. +- Tidak dapat mengubah pengaturan toko. + +### 5.3 Guest (tanpa login) +- Tidak diizinkan. Semua perangkat harus login terlebih dahulu. + +## 6. Fitur Utama + +### 6.1 Autentikasi +- Screen login (email + password) menggunakan Supabase Auth. +- Logout. +- Role ditentukan dari kolom `role` di tabel `profiles` Supabase. +- Session disimpan lokal; startup otomatis login jika session masih valid. + +### 6.2 Manajemen Produk (Admin only) +- CRUD produk: nama, barcode/no. produk, harga umum, harga reseller, stok. +- Pencarian produk berdasarkan nama atau barcode. +- Indikator stok habis (label "Habis" + opacity reduced). +- Input harga menggunakan format Rupiah otomatis (`RupiahInputFormatter`): pengguna mengetik angka mentah, field otomatis menampilkan `Rp XX.XXX`. +- **Scan barcode produk**: tombol scan di form "Tambah Produk" menggunakan kamera HP. Setelah barcode discan, hasil scan otomatis diisi ke field **"Barcode / No. Produk"** (bukan nama). Admin tetap mengisi nama produk, harga, dan stok secara manual. +- Di list produk, barcode ditampilkan di bawah nama produk untuk memudahkan identifikasi. +- Seed data otomatis jika tabel produk kosong. + +### 6.3 Transaksi Kasir (Admin & Kasir) +- Toggle tipe pembeli: Umum / Reseller (global per transaksi). +- Fitur harga reseller dapat dinonaktifkan dari **Pengaturan Toko → Mode Reseller Aktif**. Jika dimatikan: toggle Pembeli (Umum/Reseller) dan badge per-item (Reseller/Umum) disembunyikan, semua harga otomatis Umum. +- Tambah produk ke keranjang dengan 1 tap. +- Override harga per line: setiap item di keranjang dapat di-toggle antara Umum / Reseller. +- Qty per item, dengan batas stok. +- Diskon transaksi (Rp). +- Perhitungan otomatis: subtotal, diskon, total, bayar, kembalian. + +### 6.4 Keranjang (Cart) +- Bottom bar ringkas menampilkan jumlah item & total. +- Draggable bottom sheet untuk detail keranjang. +- Tombol "Kosongkan" keranjang. +- Input diskon dengan format Rupiah otomatis. +- Tombol "Bayar" mengarah ke dialog pembayaran. + +### 6.5 Pembayaran +- Dialog pembayaran scrollable (mengantisipasi keyboard). +- Input "Uang Dibayar" dengan format Rupiah otomatis dan kalkulasi kembalian realtime. +- **Pemilihan metode pembayaran**: Tunai, Bank, QRIS, Split. +- Chip cepat untuk Tunai: Uang Pas, +5rb, +10rb, +20rb, +50rb, +100rb. +- **Bank/QRIS**: tampilkan informasi petunjuk + input jumlah + status Lunas/Kurang. +- **Split Payment**: input pembayaran gabungan (Tunai + Bank + QRIS) dengan total split real-time. +- Validasi minimal pembayaran >= total untuk Tunai. +- Tombol "Selesai & Cetak" menyelesaikan transaksi. Saat diproses, tombol menampilkan indikator loading (spinner + teks "Memproses...") dan terkunci agar tidak bisa diklik dua kali. +- Jika offline, transaksi disimpan ke queue lokal dan disinkronkan otomatis saat koneksi kembali. + +### 6.6 Struk / Nota +- Dialog struk setelah pembayaran berhasil. +- Menampilkan: daftar item, diskon, total, bayar, kembali, tanggal, ID transaksi. +- Tombol "Tutup". + +### 6.7 Riwayat Transaksi +- **Urutan**: transaksi terbaru tampil di paling atas (baik untuk kasir maupun admin). +- **Kasir**: menampilkan transaksi **hanya hari ini** (tanggal berjalan). +- **Admin**: menampilkan **transaksi bulan berjalan** secara default, dengan opsi **filter rentang tanggal** menggunakan date range picker untuk melihat data periode lain. +- **Export**: Admin dapat export laporan transaksi dalam format **PDF**. Export **CSV/Excel** ditunda untuk pengembangan berikutnya. +- Summary cards dalam bentuk **horizontal slider/carousel** dengan dot indicator: + - **Pendapatan Hari Ini** vs Kemarin (persentase perubahan). + - **Pendapatan Bulan Ini** vs Bulan Lalu. + - **Laba Kotor Bulan Ini** vs Bulan Lalu. + - **Transaksi Bulan Ini** vs Bulan Lalu. + - Swipe kiri/kanan untuk berpindah antar card. + - Dot indicator di bawah slider menandakan card aktif. + - Card aktif menampilkan detail lengkap, card non-aktif menampilkan ringkas. +- List transaksi menampilkan: total, tanggal & waktu, jumlah item, ID transaksi. +- Tap pada item transaksi membuka dialog detail struk (daftar item, diskon, total, bayar, kembali, tanggal, ID transaksi). +- Setiap item di dialog detail menampilkan badge **"Reseller"** atau **"Umum"** sesuai tipe harganya. +- Dialog detail riwayat menampilkan **Metode Pembayaran** (Tunai/Bank/QRIS/Split Payment). +- Jika Split Payment, menampilkan breakdown per metode beserta jumlahnya. +- Dialog detail riwayat memiliki tombol **"Cetak Struk"** yang mengirim struk ke thermal printer Bluetooth (ESC/POS) — mirip dengan cetak dari dialog pembayaran kasir. + +### 6.9 Retur / Pembatalan Transaksi (Admin only) +- Admin dapat membatalkan transaksi dari dialog detail riwayat. +- Saat dibatalkan, stok produk secara otomatis dikembalikan ke jumlah semula. +- Transaksi yang dibatalkan ditandai dengan label **"DIBATALKAN"** dan tidak masuk hitungan pendapatan. +- Tombol **"Batalkan Transaksi"** hanya muncul untuk admin dan hanya pada transaksi yang belum dibatalkan. +- Konfirmasi dialog sebelum pembatalan: "Stok akan dikembalikan secara otomatis. Tindakan ini tidak dapat dibatalkan." + +### 6.10 Stok Minimum & Notifikasi +- Setiap produk memiliki field **Stok Minimum** (default: 5) yang dapat diatur saat tambah/edit produk. +- Di list produk, stok yang di bawah minimum akan menampilkan badge peringatan berwarna oranye: **"⚠ Stok rendah (X/Y)"**. +- Stok habis tetap menampilkan badge merah **"Stok habis"**. +- Field stok minimum ditambahkan di form tambah produk dan form edit produk. + +### 6.11 Laba / Rugi +- Setiap produk memiliki field **Harga Pokok (modal)** yang dapat diatur saat tambah/edit produk. +- Di **Riwayat**, menampilkan **Laba Kotor** per transaksi: `Pendapatan - Harga Pokok`. +- **Kasir**: melihat **Laba Hari Ini**. +- **Admin**: melihat **Laba Kotor Total** (semua transaksi) dan **Laba Kotor** per periode filter. +- Laba kotor dihitung otomatis saat checkout berdasarkan harga pokok yang tersimpan di produk. +- Transaksi yang dibatalkan tidak masuk hitungan laba/rugi. + +### 6.12 Pengaturan Toko (Admin only) +- Nama toko. +- Mata uang default (default: IDR). +- Toggle mode reseller (aktif/nonaktif). + +## 7. Screen / Menu Structure + +### 7.1 Login Screen +- Email + password. +- Tombol "Masuk". +- Loading indicator selama inisialisasi AppState. +- Error handling (invalid credentials). +- Layout: `SafeArea` + `SingleChildScrollView` dengan padding dinamis untuk keyboard. + +### 7.2 AuthGate (main.dart) +- `StreamBuilder` + `Selector` untuk mengecek: + 1. `state.loading` → tampilkan `CircularProgressIndicator`. + 2. `state.isLoggedIn` → tampilkan `HomePage`. + 3. Selain itu → tampilkan `LoginScreen`. +- Listener `onAuthStateChange` di `AppState` untuk update `userId` dan `userRole` otomatis. + +### 7.3 HomePage (bottom nav) +- **AppBar**: judul "Dutra Store" + icon logout. +- **Body**: `IndexedStack` dengan screens sesuai role. +- **BottomNavigationBar**: + - **Kasir**: 2 tab (`Kasir`, `Riwayat`). + - **Admin**: 5 tab (`Kasir`, `Produk`, `Riwayat`, `Akun`, `Pengaturan`). +- Navigasi menggunakan `_index` yang direset ke 0 jika role berubah. + +### 7.4 Kasir Screen +- Search bar + segmented button tipe pembeli (Umum/Reseller). +- Grid produk 2 kolom. +- Bottom bar: jumlah item + total + icon expand. +- Draggable bottom sheet keranjang. +- Dialog pembayaran + struk. + +### 7.5 Produk Screen +- Search bar + form tambah/edit produk. +- Grid daftar produk. +- Hanya admin yang melihat tab ini. + +### 7.6 Riwayat Screen +- **Admin**: date range picker untuk filter transaksi berdasarkan tanggal. +- Summary cards: + - **Kasir**: Transaksi Hari Ini, Pendapatan Hari Ini. + - **Admin**: Semua Transaksi, Total Pendapatan, Jumlah Semua Transaksi. +- List transaksi: + - **Kasir**: hanya transaksi hari ini. + - **Admin**: semua transaksi atau sesuai filter tanggal. +- Setiap item: total, tanggal & waktu, jumlah item, ID transaksi. + +### 7.7 Kelola Akun Kasir (Admin only) +- Screen untuk mengelola akun kasir. +- Form tambah akun kasir: email, password, nama lengkap. +- List akun kasir yang ada dengan opsi hapus. +- Setiap akun memiliki role `kasir` di tabel `profiles`. + +### 7.8 Pengaturan Toko (Admin only) +- Screen untuk mengubah pengaturan toko. +- Field: nama toko, mata uang (default: IDR), alamat printer Bluetooth. +- Toggle mode reseller (aktif/nonaktif). +- Pengaturan disimpan di `shared_preferences`. + +### 7.9 Login/Logout Flow +- Login: `LoginScreen` → `AppState.login()` → update `userId` + `userRole` → `AuthGate` otomatis navigate ke `HomePage`. +- Logout: icon logout di AppBar → `AppState.logout()` → clear cart + discount → `AuthGate` otomatis navigate ke `LoginScreen`. + +## 8. Model Data + +### Product +| Field | Tipe | Keterangan | +|-------|------|-----------| +| id | text (PK) | UUID unik | +| name | text | Nama produk | +| barcode | text | Barcode / No. Produk (opsional) | +| price | number | Harga umum | +| price_reseller | number | Harga reseller | +| stock | integer | Stok tersedia | +| min_stock | integer | Batas stok minimum untuk peringatan (default: 5) | +| harga_pokok | number | Harga modal per unit (untuk hitung laba kotor) | + +### Sale +| Field | Tipe | Keterangan | +|-------|------|-----------| +| id | text (PK) | UUID unik | +| created_at | timestamp | Waktu transaksi | +| items | jsonb | Array of {name, price, qty, isReseller} | +| subtotal | number | Total sebelum diskon | +| discount | number | Diskon transaksi | +| total | number | subtotal - discount | +| paid | number | Jumlah dibayar | +| change | number | paid - total | +| user_id | text (FK) | ID user yang melakukan transaksi (opsional) | +| is_cancelled | boolean | true jika transaksi dibatalkan (default: false) | +| total_cost | number | Total harga pokok dari item yang terjual (untuk laba kotor) | +| payment_method | text | Metode pembayaran: 'tunai' (default), 'bank', 'qris', 'split' | +| split_payment | jsonb | Object pembayaran gabungan: {"tunai": 50000, "bank": 100000, "qris": 50000} (opsional) | + +### CartLine (lokal) +| Field | Tipe | Keterangan | +|-------|------|-----------| +| product | Product | Referensi produk | +| qty | int | Jumlah | +| isReseller | bool | true = harga reseller dipakai | + +### Profile (Supabase) +| Field | Tipe | Keterangan | +|-------|------|-----------| +| id | uuid (FK auth.users) | Referensi user | +| role | text | 'admin' atau 'kasir' | +| full_name | text | Nama lengkap (opsional) | + +## 8.1 Utilitas Format Rupiah +- `RupiahInputFormatter`: `TextInputFormatter` untuk field harga/uang. +- Saat pengguna mengetik angka, field otomatis menampilkan format `Rp XX.XXX` (contoh: `50000` → `Rp 50.000`). +- `RupiahInputFormatter.getRawValue(String)`: mengembalikan nilai `int?` dari string yang diformat, untuk kebutuhan perhitungan. +- Digunakan pada: + - Form tambah/edit produk: `Harga Umum`, `Harga Reseller`. + - Dialog pembayaran: `Uang Dibayar`. + - Keranjang: `Diskon`. + +## 9. Alur Transaksi +1. User login → role ditentukan → navigasi sesuai role. +2. **Kasir**: + - Pilih tipe pembeli (Umum / Reseller). + - Tambah produk ke keranjang. + - Sesuaikan qty & tipe harga per item. + - Isi diskon (opsional). + - Tekan "Bayar" → dialog pembayaran muncul. + - Input uang dibayar / pilih chip cepat. + - Validasi, lalu checkout → simpan ke Supabase, kurangi stok. + - Tampilkan dialog struk. + - Tutup struk → kembali ke tab Kasir dengan keranjang kosong. +3. **Admin**: + - Dapat melakukan transaksi seperti kasir. + - Dapat menambah/edit/hapus produk. + - Dapat melihat riwayat & laporan. + - Dapat mengelola akun kasir & pengaturan toko. + +## 10. UI / UX Requirements +- Tema gelap dengan aksen amber. +- Kartu produk dengan sudut rounded, shadow, avatar inisial nama. +- Bottom sheet keranjang dengan handle drag. +- Semua dialog yang berpotensi overflow harus menggunakan scroll view. +- Label dan mata uang dalam Bahasa Indonesia (Rupiah). +- UI menyesuaikan role: tombol/fitur yang tidak diizinkan disembunyikan (tidak hanya di-disable). + +### 10.1 Design System +- **Tema utama:** Dark theme. Warna aksen: amber. +- **Radius:** 18 (kartu), 12 (input/dialog), 8 (chip/tag). +- **Spacing:** padding screen/list `EdgeInsets.all(12)`, padding form/dialog `EdgeInsets.all(16)`, gap field `SizedBox(height: 10)`, gap section `SizedBox(height: 14)`. +- **Kartu:** padding minimal 12, jangan hardcode tinggi. Jika 3+ field, prioritaskan wrap/scroll. +- **Input:** label jelas, helper text untuk opsional. Jika form panjang, bungkus `SingleChildScrollView` + padding bottom `MediaQuery.of(context).viewInsets.bottom` agar tidak tertutup keyboard. +- **Tombol:** primary = `FilledButton` (aksi utama: Bayar, Tambah, Simpan), destructive = merah (`kDanger`), secondary = `TextButton`/`OutlinedButton`. + +### 10.2 Responsif & Overflow +- **Grid Kasir:** 2 kolom di HP, 3–4 kolom di tablet (lebar > 600dp). Hindari `childAspectRatio` tetap; pakai `AspectRatio(1.1)` atau biarkan grid menentukan tinggi. +- **Bottom Sheet:** keranjang harus berupa bottom sheet (bukan panel tetap), bisa di-drag, konten selalu scrollable (`SingleChildScrollView` tanpa `Expanded`). +- **Dialog:** input panjang harus scrollable. Jangan pakai `Expanded` di dalam dialog yang bisa overflow. +- **Produk:** form + list dalam satu halaman scroll (`SingleChildScrollView` + `ListView.shrinkWrap`). +- **Teks:** jangan hardcode font size. Batasi nama produk max 2 baris (`maxLines: 2`, `overflow: TextOverflow.ellipsis`). + +### 10.3 UX Kasir (Critical Path) +- Target: transaksi selesai dalam 3 tap (pilih → bayar → selesai). +- Tampilkan total, diskon, kembalian real-time. +- Tipe pembeli pakai segmented button (Umum/Reseller), bukan dropdown. +- Setiap item keranjang bisa ubah qty atau tipe harga dalam 1 tap. +- Stok habis: tampil badge merah "Habis" + matikan visual/tap. +- Stok menipis: badge peringatan oranye sebelum habis. + +### 10.4 Aksesibilitas & Feedback +- Minimal tap target: 44x44dp. +- Kontras teks minimal 4.5:1. +- Jangan andal warna saja (tambah ikon/label). Contoh: stok habis = badge merah + teks "Habis". +- Setiap aksi ada `SnackBar` feedback: sukses hijau, error merah, info biru/abu. +- Loading state untuk operasi > 500ms (`CircularProgressIndicator(color: kAccent)`). + +### 10.5 Role-Based Visibility +- Fitur tidak diizinkan untuk role tertentu harus **disembunyikan sepenuhnya**, bukan cuma di-disable. +- Admin: lihat semua transaksi + filter tanggal + aksi batalkan. +- Kasir: lihat transaksi hari ini, tidak ada aksi batalkan/filter. + +### 10.6 Reusability & Konsistensi +- Buat widget reuseable untuk komponen berulang: `_Tag`, `_ReportCard`, `_Avatar`, `_Stepper`. +- Taruh konstanta warna/spacing di `lib/utils/colors.dart`. +- Konsisten pakai `formatRupiah()` untuk semua angka mata uang. + +### 10.7 Checklist Sebelum Submit Perubahan UI/UX +- [ ] `flutter analyze` → No issues found (tanpa error). +- [ ] Coba di layar kecil (HP 5") dan besar (tablet). +- [ ] Coba dengan keyboard muncul (input uang/diskon). +- [ ] Pastikan tidak ada hardcoded height yang bikin overflow. +- [ ] Semua teks dalam Bahasa Indonesia. +- [ ] Konsisten pakai `formatRupiah()` untuk angka mata uang. + +## 11. Non-Fitur (Out of Scope untuk versi ini) +- ~~Printer thermal Bluetooth (direncanakan Sprint 4).~~ ✅ Sudah diimplementasikan (Sprint 4). +- ~~Laporan bulanan / export PDF/Excel.~~ ✅ Sudah diimplementasikan (export PDF & CSV di Sprint 3/4). +- ~~Barcode scanner.~~ ✅ Sudah diimplementasikan (Sprint 2, `mobile_scanner`). +- Multi-cabang / multi-toko. + +## 12. Kebutuhan Non-Fungsional +- Sinkronisasi realtime < 2 detik antar perangkat. +- Offline mode: data terbaru tetap tampil meskipun koneksi terputus (cache lokal). +- Build APK debug untuk emulator Android 13+. +- Session auth harus aman (token disimpan aman, auto-logout setelah inactivity opsional). + +## 13. Risiko & Mitigasi +| Risiko | Mitigasi | +|--------|----------| +| Stok menjadi negatif | Validasi di `addToCart` & `changeQty` dibatasi oleh stok produk. | +| Data inkonsistenan saat并发 | Supabase realtime + operasi atomic di sisi backend. | +| Keyboard menutupi input di dialog | Semua dialog input menggunakan `SingleChildScrollView`. | +| Akses tidak sah | Role-based UI + validasi di Supabase (RLS policies). | +| Koneksi putus saat checkout | Simpan transaksi ke queue lokal, kirim saat koneksi kembali (opsional). | + +## 14. Sprint Breakdown + +### Sprint 0 — Foundation (Selesai) +- [x] Setup Flutter + Provider + Supabase. +- [x] Struktur dasar: screens, models, state, utils. +- [x] CRUD Produk + Realtime stream. +- [x] Dual pricing (Umum / Reseller). +- [x] UI redesign (dark theme, amber accent). + +### Sprint 1 — Transaksi Kasir (Selesai) +- [x] Tab Kasir: grid produk + search + tipe pembeli. +- [x] Cart: bottom bar + bottom sheet + qty control. +- [x] Diskon transaksi. +- [x] Dialog pembayaran + kalkulasi kembalian. +- [x] Dialog struk. +- [x] Fix overflow (Produk tab, Kasir dialog, Cart sheet). + +### Sprint 2 — Auth & Role-Based Access (Selesai) +- [x] Setup Supabase Auth (email + password). +- [x] Tabel `profiles` dengan kolom `role`. +- [x] Screen login + loading state + error handling. +- [x] Logout icon di AppBar. +- [x] Integrasi role ke AppState (`userId`, `userRole`, `isAdmin`, `isKasir`, `isLoggedIn`). +- [x] Auth state listener (`onAuthStateChange`) untuk update otomatis saat login/logout. +- [x] UI adaptif sesuai role: + - Bottom nav: Kasir (2 tab), Admin (3 tab). + - Riwayat: Kasir lihat hari ini, Admin lihat semua. + - Produk: hanya admin. +- [x] Seed admin default via `_seedAdminIfEmpty()`. +- [x] Audit trail: tambah `user_id` pada model `Sale` dan simpan saat checkout. +- [x] Fix bottom nav assertion error untuk role kasir (nav disembunyikan jika < 2 item). +- [x] Fix login screen stuck/overflow dengan `SafeArea` + `SingleChildScrollView` + padding dinamis. +- [x] Optimasi `AuthGate` dengan `Selector` agar tidak rebuild berlebihan. +- [x] Rupiah input formatter untuk field harga/uang di Produk, Pembayaran, dan Diskon. +- [x] Scan barcode produk di form Produk menggunakan `mobile_scanner` + permission kamera. + +### Sprint 3 — Admin Features +- [x] Riwayat transaksi dengan filter role-based (kasir: hari ini, admin: semua). +- [x] Summary cards adaptif sesuai role. +- [x] Filter date range untuk admin di riwayat menggunakan date range picker. +- [x] Manajemen akun kasir (tambah/hapus akun kasir dari dalam app). +- [x] Edit akun kasir (ubah nama/email/password via dialog edit, password pakai `auth.admin.updateUserById`). +- [x] Pengaturan toko (nama toko, mata uang, toggle reseller). +- [x] Export laporan ke PDF dan CSV (Excel) menggunakan `pdf`, `csv`, `path_provider`, dan `share_plus`. + +### Sprint 4 — Polish & Integration +- [x] Export laporan ke PDF dan CSV (Excel) menggunakan `pdf`, `csv`, `path_provider`, dan `share_plus`. +- [x] Offline mode improvements (queue transaksi menggunakan `OfflineQueueService` + `connectivity_plus`). +- [x] Thermal printer Bluetooth (package `print_bluetooth_thermal` + `esc_pos_utils_plus`, ganti dari `blue_thermal_printer` yang gagal build). +- [x] Cetak struk langsung dari dialog pembayaran kasir. +- [x] Retur / Pembatalan transaksi (admin dapat batalkan transaksi dari riwayat, stok otomatis dipulihkan). +- [x] Stok minimum & notifikasi (field min_stock di produk, badge warning di list produk). +- [x] Laba / Rugi (harga pokok per produk, laporan laba kotor di riwayat). +- [x] Build release APK untuk distribusi. +- [ ] Testing & bug fixing menyeluruh. + +## 15. Status Implementasi Saat Ini + +### Fitur yang Sudah Berjalan +- ✅ Login/logout dengan Supabase Auth +- ✅ Role-based access: Admin (3 tab: Kasir, Produk, Riwayat, Pengaturan) dan Kasir (2 tab) — Akun Kasir & Printer digabung ke dalam tab Pengaturan +- ✅ CRUD Produk dengan barcode scanner +- ✅ Transaksi kasir dengan dual pricing (Umum/Reseller) +- ✅ Mode Reseller dapat dinyalakan/matikan dari Pengaturan Toko (saat mati, toggle harga reseller di kasir disembunyikan) +- ✅ Cart bottom sheet + diskon + pembayaran + struk +- ✅ Pembayaran: tombol "Selesai & Cetak" pakai loading guard (spinner + "Memproses...") agar tidak dobel klik +- ✅ Riwayat transaksi: terurut terbaru di atas, filter role-based, date range +- ✅ Detail riwayat: badge per-item "Reseller"/"Umum" + tombol "Cetak Struk" +- ✅ Manajemen akun kasir (tambah/hapus/edit) +- ✅ Pengaturan toko (nama, mata uang, toggle reseller) — nama app "Dutra Store" +- ✅ Export laporan PDF +- ⏸️ Export laporan CSV/Excel (ditunda untuk pengembangan berikutnya) +- ✅ Offline mode queue untuk transaksi +- ✅ Thermal printer Bluetooth (scan, connect, auto-reconnect, cetak struk ESC/POS) +- ✅ Cetak struk dari riwayat (tap transaksi → dialog detail → tombol "Cetak Struk") +- ✅ Rupiah input formatter +- ✅ Overflow fixes pada semua screen +- ✅ Retur/Pembatalan transaksi (admin dapat batalkan dari dialog detail riwayat, stok otomatis dipulihkan) +- ✅ Stok minimum & notifikasi (badge warning stok rendah di list produk) +- ✅ Laba/Rugi (harga pokok per produk, laporan laba kotor di riwayat: Laba Hari Ini untuk kasir, LABA KOTOR untuk admin) +- ✅ Tab Riwayat: summary cards compact (tap untuk expand), list transaksi ditampilkan di bawah summary, detail transaksi menggunakan bottom sheet +- ✅ Tab Riwayat: ringkasan bulanan dengan perbandingan MoM (Pendapatan, Laba Kotor, Transaksi) untuk admin +- ✅ Tab Riwayat: admin melihat transaksi bulan berjalan secara default (bukan semua transaksi) +- ✅ Tab Riwayat: summary cards dalam bentuk horizontal slider/carousel dengan dot indicator, swipe kiri/kanan untuk pindah card, card aktif menampilkan detail lengkap +- ✅ Tab Produk: form tambah produk dipindah ke bottom sheet (FAB + Tambah Produk), list produk tetap terlihat +- ✅ Tab Kasir: animasi pulse di cart bar saat produk ditambahkan +- ✅ Dialog pembayaran: loading overlay + disable input saat proses checkout + minimum 300ms visibility +- ✅ Dialog pembayaran: pilihan metode pembayaran (Tunai, Bank, QRIS, Split) dengan chip selector +- ✅ Dialog pembayaran: chip cepat untuk Tunai (Uang Pas, +5rb, +10rb, +20rb, +50rb, +100rb) +- ✅ Dialog pembayaran: split payment support dengan total split real-time +- ✅ Receipt & detail riwayat: menampilkan metode pembayaran dan breakdown split payment +- ✅ Sale model: field payment_method + split_payment untuk dokumentasi transaksi +- ✅ Release APK (app-release.apk 66.9MB) + +### Fitur yang Didefer / Belum +- ✅ Ganti password akun kasir via Supabase admin API (`auth.admin.updateUserById` tersedia di gotrue 2.26.0). +- ✅ Testing & bug fixing menyeluruh (analyzer `No issues found!`, 0 error/warning). +- ⏳ Testing & bug fixing menyeluruh (belum dilakukan comprehensive testing). +- ✅ Build release APK untuk distribusi (app-release.apk 66.9MB). + +### Catatan Teknis +- Nama aplikasi: **Dutra Store** (launcher label, AppBar, judul login, export). +- Admin tab dikurangi: Akun Kasir & Printer digabung ke dalam tab **Pengaturan** (admin sekarang 3 tab: Produk, Riwayat, Pengaturan). +- Printer auto-connect saat app start (MAC tersimpan di shared_preferences). +- `flutter analyze` sekarang **No issues found!** (semua `withOpacity` diganti `withValues(alpha:)`, `use_build_context_synchronously` di-handle, dead code dihapus). +- App sudah di-deploy ke device: **TECNO KM4** (Android 15) dan **RMX2061** (Android 11 API 30), keduanya berjalan normal. +- **Database migration**: + 1. Jalankan SQL di `supabase/migrations/20240101_add_cancel_and_min_stock.sql` untuk kolom `is_cancelled` (sales) dan `min_stock` (products). + 2. Jalankan SQL di `supabase/migrations/20240102_add_harga_pokok_and_profit.sql` untuk kolom `harga_pokok` (products) dan `total_cost` (sales). + 3. Jalankan SQL di `supabase/migrations/20240103_add_payment_method.sql` untuk kolom `payment_method` dan `split_payment` (sales) — **sudah dijalankan**. +- UI/UX skill tersimpan di `.kilo/agent/uiux-pos-grosir.md` dan bagian PRD 10.1-10.7. +- Color scheme: brand amber dominant di Kasir & Produk, hijau untuk harga umum, merah untuk error/habis, abu untuk muted. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a916eb5 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# app_grosir + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..e836924 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.grosir.app_grosir" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.grosir.app_grosir" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5c18006 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/grosir/app_grosir/MainActivity.kt b/android/app/src/main/kotlin/com/grosir/app_grosir/MainActivity.kt new file mode 100644 index 0000000..f90d297 --- /dev/null +++ b/android/app/src/main/kotlin/com/grosir/app_grosir/MainActivity.kt @@ -0,0 +1,5 @@ +package com.grosir.app_grosir + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..82656b0 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..ea41c91 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..901c8fe Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..5cfeb0a Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..57e2e81 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..4c0f87b --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html new file mode 100644 index 0000000..0ad7bec --- /dev/null +++ b/android/build/reports/problems/problems-report.html @@ -0,0 +1,663 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..f018a61 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac3b479 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..fb605bc --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.9.1" apply false + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 0000000..de080e2 Binary files /dev/null and b/assets/logo.png differ diff --git a/check_addform.py b/check_addform.py new file mode 100644 index 0000000..9df7224 --- /dev/null +++ b/check_addform.py @@ -0,0 +1,38 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +stack = [] +for i in range(179, 448): + line = lines[i] + in_string = False + escape = False + for j, c in enumerate(line): + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + stack.append((i+1, j+1)) + elif c == ')': + if stack: + stack.pop() + else: + print(f'Unexpected ) at line {i+1}:{j+1}') + break + else: + continue + break +else: + if stack: + print(f'Unclosed ( at:') + for item in stack: + print(f' Line {item[0]}:{item[1]}') + else: + print('All balanced!') diff --git a/check_addform_balance.py b/check_addform_balance.py new file mode 100644 index 0000000..561eba1 --- /dev/null +++ b/check_addform_balance.py @@ -0,0 +1,39 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +# Check bracket balance for _showAddForm (lines 180-431) +stack = [] +for i in range(179, 431): + line = lines[i] + in_string = False + escape = False + for j, c in enumerate(line): + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + stack.append((i+1, j+1, line.rstrip())) + elif c == ')': + if stack: + stack.pop() + else: + print(f'Unexpected ) at line {i+1}:{j+1}') + break + else: + continue + break +else: + if stack: + print(f'Unclosed ( at:') + for item in stack: + print(f' Line {item[0]}:{item[1]} | {item[2]}') + else: + print('All balanced!') diff --git a/check_addform_parens.py b/check_addform_parens.py new file mode 100644 index 0000000..10f2e8a --- /dev/null +++ b/check_addform_parens.py @@ -0,0 +1,15 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +opens = 0 +closes = 0 +for i in range(179, 431): + line = lines[i] + o = line.count('(') + c = line.count(')') + opens += o + closes += c + if o != 0 or c != 0: + print(f'{i+1}: +{o}-{c} = {opens-closes} | {line.rstrip()}') + +print(f'\nTotal (: {opens}, ): {closes}, diff: {opens-closes}') diff --git a/check_addform_parens2.py b/check_addform_parens2.py new file mode 100644 index 0000000..e940615 --- /dev/null +++ b/check_addform_parens2.py @@ -0,0 +1,27 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +opens = 0 +closes = 0 +for i in range(179, 436): + line = lines[i] + in_string = False + escape = False + for c in line: + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + opens += 1 + elif c == ')': + closes += 1 + +print(f'Total (: {opens}, ): {closes}, diff: {opens-closes}') diff --git a/check_depth.py b/check_depth.py new file mode 100644 index 0000000..efc8d74 --- /dev/null +++ b/check_depth.py @@ -0,0 +1,16 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +depth = 0 +for i in range(493, 644): + line = lines[i] + o = line.count('(') + c = line.count(')') + if depth == 0 and (o != 0 or c != 0): + print(f'Depth became 0 at line {i+1}: {line.rstrip()}') + depth += o - c + if depth < 0: + print(f'Negative depth at line {i+1}: {line.rstrip()}') + break + +print(f'Final depth: {depth}') diff --git a/check_depth2.py b/check_depth2.py new file mode 100644 index 0000000..7a23fd0 --- /dev/null +++ b/check_depth2.py @@ -0,0 +1,10 @@ +with open('D:\\app\\ai\\app-grosir\\test_syntax2.dart', 'r') as f: + lines = f.readlines() + +depth = 0 +for i, line in enumerate(lines): + opens = line.count('(') + closes = line.count(')') + if opens != 0 or closes != 0 or depth != 0: + depth += opens - closes + print(f'{i+1}: +{opens}-{closes} = {depth} | {line.rstrip()}') diff --git a/check_parens.py b/check_parens.py new file mode 100644 index 0000000..794b6e8 --- /dev/null +++ b/check_parens.py @@ -0,0 +1,15 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +opens = 0 +closes = 0 +for i in range(493, 644): + line = lines[i] + o = line.count('(') + c = line.count(')') + opens += o + closes += c + if o != 0 or c != 0: + print(f'{i+1}: +{o}-{c} = {opens-closes} | {line.rstrip()}') + +print(f'Total (: {opens}, ): {closes}') diff --git a/check_parens_detail.py b/check_parens_detail.py new file mode 100644 index 0000000..c9b42be --- /dev/null +++ b/check_parens_detail.py @@ -0,0 +1,23 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +for i in range(493, 644): + line = lines[i] + in_string = False + escape = False + for j, c in enumerate(line): + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + print(f'{i+1}:{j+1} OPEN | {line.rstrip()}') + elif c == ')': + print(f'{i+1}:{j+1} CLOSE | {line.rstrip()}') diff --git a/check_parens_no_strings.py b/check_parens_no_strings.py new file mode 100644 index 0000000..fd0aece --- /dev/null +++ b/check_parens_no_strings.py @@ -0,0 +1,29 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +depth = 0 +for i in range(493, 644): + line = lines[i] + in_string = False + escape = False + for c in line: + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + depth += 1 + elif c == ')': + depth -= 1 + if depth < 0: + print(f'Negative depth at line {i+1}: {line.rstrip()}') + break + +print(f'Final depth: {depth}') diff --git a/check_strings.py b/check_strings.py new file mode 100644 index 0000000..c1cdf89 --- /dev/null +++ b/check_strings.py @@ -0,0 +1,23 @@ +with open('D:\\app\\ai\\app-grosir\\test_syntax2.dart', 'r') as f: + lines = f.readlines() + +for i, line in enumerate(lines): + stripped = line.strip() + if stripped.startswith('//') or stripped.startswith('/*') or stripped.startswith('*'): + continue + in_string = False + escape = False + for j, c in enumerate(line): + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + if not in_string: + in_string = True + else: + in_string = False + if in_string: + print(f'Unclosed string at line {i+1}: {line.rstrip()}') diff --git a/check_unclosed.py b/check_unclosed.py new file mode 100644 index 0000000..56225fa --- /dev/null +++ b/check_unclosed.py @@ -0,0 +1,38 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +stack = [] +for i in range(493, 644): + line = lines[i] + in_string = False + escape = False + for j, c in enumerate(line): + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + stack.append((i+1, j+1, line.rstrip())) + elif c == ')': + if stack: + stack.pop() + else: + print(f'Unexpected ) at line {i+1}:{j+1}') + break + else: + continue + break +else: + if stack: + print(f'Unclosed ( at:') + for item in stack: + print(f' Line {item[0]}:{item[1]} | {item[2]}') + else: + print('All balanced!') diff --git a/check_unclosed2.py b/check_unclosed2.py new file mode 100644 index 0000000..e2130c2 --- /dev/null +++ b/check_unclosed2.py @@ -0,0 +1,38 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +stack = [] +for i in range(493, 649): + line = lines[i] + in_string = False + escape = False + for j, c in enumerate(line): + if escape: + escape = False + continue + if c == '\\': + escape = True + continue + if c in "'\"": + in_string = not in_string + continue + if in_string: + continue + if c == '(': + stack.append((i+1, j+1, line.rstrip())) + elif c == ')': + if stack: + stack.pop() + else: + print(f'Unexpected ) at line {i+1}:{j+1}') + break + else: + continue + break +else: + if stack: + print(f'Unclosed ( at:') + for item in stack: + print(f' Line {item[0]}:{item[1]} | {item[2]}') + else: + print('All balanced!') diff --git a/fix_indent.py b/fix_indent.py new file mode 100644 index 0000000..3eab4cb --- /dev/null +++ b/fix_indent.py @@ -0,0 +1,35 @@ +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'r') as f: + lines = f.readlines() + +# Find the start and end of _showAddForm +start = None +end = None +for i, line in enumerate(lines): + if line.strip().startswith('void _showAddForm'): + start = i + if start is not None and line.strip() == '}' and i > start + 5: + # Check if this is the end of _showAddForm + # It should be followed by empty line or another top-level declaration + if i + 1 < len(lines): + next_line = lines[i + 1].strip() + if next_line == '' or next_line.startswith('void ') or next_line.startswith('class '): + end = i + break + +print(f'_showAddForm: lines {start+1} to {end+1}') + +# Remove 2-space indent from _showAddForm function +for i in range(start, end + 1): + if lines[i].startswith(' '): + lines[i] = lines[i][2:] + +# After _showAddForm, there might be an extra class closing } +# The class _ProdukScreenState should close right after build method +# Let's find the class closing after _showAddForm and remove it if it's extra +# After _showAddForm ends, the next line should be empty or a function/class +# If there's a } followed by empty line and then another }, remove the first } + +with open('D:\\app\\ai\\app-grosir\\lib\\screens\\produk_screen.dart', 'w') as f: + f.writelines(lines) + +print('Done') diff --git a/git.txt b/git.txt new file mode 100644 index 0000000..e3b6ff4 --- /dev/null +++ b/git.txt @@ -0,0 +1 @@ +https://github.com/HiiTayo/app-grosir.git \ No newline at end of file diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..1dc6cf7 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..ac6a04d --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,616 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..85a5ca5 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + App Grosir + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + app_grosir + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..0365c33 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,176 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import 'config.dart'; +import 'state/app_state.dart'; +import 'services/printer_service.dart'; +import 'screens/login_screen.dart'; +import 'screens/home_page.dart'; +import 'utils/colors.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + await Supabase.initialize(url: supabaseUrl, publishableKey: supabaseAnonKey); + await printerService.init(); + runApp(const MyApp()); +} + +class MyApp extends StatefulWidget { + const MyApp({super.key}); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State with WidgetsBindingObserver { + late final AppState _appState; + + @override + void initState() { + super.initState(); + _appState = AppState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _appState.stopPolling(); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _appState.startPolling(); + } else { + _appState.stopPolling(); + } + } + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider.value( + value: _appState, + child: MaterialApp( + title: 'Dutra Store', + debugShowCheckedModeBanner: false, + theme: ThemeData( + useMaterial3: true, + brightness: Brightness.dark, + scaffoldBackgroundColor: kBackground, + colorScheme: ColorScheme.dark( + primary: kAccent, + secondary: kSuccess, + surface: kSurface, + onSurface: kText, + error: kDanger, + ), + appBarTheme: const AppBarTheme( + backgroundColor: kBackground, + foregroundColor: kText, + elevation: 0, + centerTitle: true, + titleTextStyle: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w700, + color: kText, + ), + ), + cardTheme: CardThemeData( + color: kSurface2, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(kRadius), + side: const BorderSide(color: kBorder), + ), + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: kSurface2, + contentPadding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide.none, + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: const BorderSide(color: kBorder), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: const BorderSide(color: kAccent, width: 1.5), + ), + labelStyle: const TextStyle(color: kMuted), + hintStyle: const TextStyle(color: kMuted), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + backgroundColor: kAccent, + foregroundColor: const Color(0xFF1A1206), + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + textStyle: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + ), + ), + ), + dialogTheme: DialogThemeData( + backgroundColor: kSurface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + titleTextStyle: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w700, + color: kText, + ), + ), + bottomNavigationBarTheme: const BottomNavigationBarThemeData( + backgroundColor: kSurface, + selectedItemColor: kAccent, + unselectedItemColor: kMuted, + selectedLabelStyle: TextStyle(fontWeight: FontWeight.w600), + type: BottomNavigationBarType.fixed, + elevation: 0, + ), + ), + home: const AuthGate(), + ), + ); + } +} + +class AuthGate extends StatelessWidget { + const AuthGate({super.key}); + + @override + Widget build(BuildContext context) { + return Selector( + selector: (context, state) => state.loading, + builder: (context, loading, child) { + if (loading) { + return const Scaffold( + body: Center( + child: CircularProgressIndicator(color: kAccent), + ), + ); + } + return Selector( + selector: (context, state) => state.isLoggedIn, + builder: (context, loggedIn, child) { + if (loggedIn) { + return const HomePage(); + } + return const LoginScreen(); + }, + ); + }, + ); + } +} diff --git a/lib/models/product.dart b/lib/models/product.dart new file mode 100644 index 0000000..b5beda9 --- /dev/null +++ b/lib/models/product.dart @@ -0,0 +1,51 @@ +class Product { + final String id; + final String name; + final String barcode; + final double price; + final double priceReseller; + final int stock; + final int minStock; + final double hargaPokok; + + Product({ + required this.id, + required this.name, + this.barcode = '', + required this.price, + this.priceReseller = 0, + required this.stock, + this.minStock = 5, + this.hargaPokok = 0, + }); + + factory Product.fromJson(Map json) { + return Product( + id: json['id'] as String, + name: json['name'] as String, + barcode: json['barcode'] != null ? json['barcode'] as String : '', + price: (json['price'] as num).toDouble(), + priceReseller: json['price_reseller'] != null + ? (json['price_reseller'] as num).toDouble() + : 0, + stock: json['stock'] as int, + minStock: json['min_stock'] != null + ? (json['min_stock'] as int) + : 5, + hargaPokok: json['harga_pokok'] != null + ? (json['harga_pokok'] as num).toDouble() + : 0, + ); + } + + Map toJson() => { + 'id': id, + 'name': name, + 'barcode': barcode, + 'price': price, + 'price_reseller': priceReseller, + 'stock': stock, + 'min_stock': minStock, + 'harga_pokok': hargaPokok, + }; +} diff --git a/lib/models/sale.dart b/lib/models/sale.dart new file mode 100644 index 0000000..b044a55 --- /dev/null +++ b/lib/models/sale.dart @@ -0,0 +1,118 @@ +class SaleItem { + final String productId; + final String name; + final double price; + final int qty; + final bool isReseller; + + SaleItem({ + required this.productId, + required this.name, + required this.price, + required this.qty, + this.isReseller = false, + }); + + double get subtotal => price * qty; + + factory SaleItem.fromJson(Map json) { + return SaleItem( + productId: json['product_id'] as String? ?? '', + name: json['name'] as String, + price: (json['price'] as num).toDouble(), + qty: json['qty'] as int, + isReseller: json['isReseller'] as bool? ?? false, + ); + } + + Map toJson() => { + 'product_id': productId, + 'name': name, + 'price': price, + 'qty': qty, + 'isReseller': isReseller, + }; +} + +class Sale { + final String id; + final DateTime date; + final String? userId; + final List items; + final double subtotal; + final double discount; + final double total; + final double paid; + final double change; + final double totalCost; + final bool isCancelled; + final String paymentMethod; + final String paymentStatus; + final double dueAmount; + final String? customerPhone; + final Map? splitPayment; + + Sale({ + required this.id, + required this.date, + this.userId, + required this.items, + required this.subtotal, + required this.discount, + required this.total, + required this.paid, + required this.change, + required this.totalCost, + this.isCancelled = false, + this.paymentMethod = 'tunai', + this.paymentStatus = 'paid', + this.dueAmount = 0.0, + this.customerPhone, + this.splitPayment, + }); + + factory Sale.fromJson(Map json) { + return Sale( + id: json['id'] as String, + date: DateTime.parse(json['created_at'] as String), + userId: json['user_id'] as String?, + items: (json['items'] as List) + .map((e) => SaleItem.fromJson(e as Map)) + .toList(), + subtotal: (json['subtotal'] as num).toDouble(), + discount: (json['discount'] as num).toDouble(), + total: (json['total'] as num).toDouble(), + paid: (json['paid'] as num).toDouble(), + change: (json['change'] as num).toDouble(), + totalCost: (json['total_cost'] as num?)?.toDouble() ?? 0, + isCancelled: json['is_cancelled'] as bool? ?? false, + paymentMethod: json['payment_method'] as String? ?? 'tunai', + paymentStatus: json['payment_status'] as String? ?? 'paid', + dueAmount: (json['due_amount'] as num?)?.toDouble() ?? 0.0, + customerPhone: json['customer_phone'] as String?, + splitPayment: json['split_payment'] != null + ? Map.from(json['split_payment'] as Map) + : null, + ); + } + + Map toJson() => { + 'id': id, + 'created_at': date.toIso8601String(), + 'user_id': userId, + 'items': items.map((e) => e.toJson()).toList(), + 'subtotal': subtotal, + 'discount': discount, + 'total': total, + 'paid': paid, + 'change': change, + 'total_cost': totalCost, + 'is_cancelled': isCancelled, + 'payment_method': paymentMethod, + 'payment_status': paymentStatus, + 'due_amount': dueAmount, + 'customer_phone': customerPhone, + if (splitPayment != null && splitPayment!.isNotEmpty) + 'split_payment': splitPayment, + }; +} diff --git a/lib/models/user_profile.dart b/lib/models/user_profile.dart new file mode 100644 index 0000000..17072b3 --- /dev/null +++ b/lib/models/user_profile.dart @@ -0,0 +1,25 @@ +class UserProfile { + final String id; + final String role; + final String? fullName; + + UserProfile({ + required this.id, + required this.role, + this.fullName, + }); + + factory UserProfile.fromJson(Map json) { + return UserProfile( + id: json['id'] as String, + role: json['role'] as String, + fullName: json['full_name'] as String?, + ); + } + + Map toJson() => { + 'id': id, + 'role': role, + 'full_name': fullName, + }; +} diff --git a/lib/screens/home_page.dart b/lib/screens/home_page.dart new file mode 100644 index 0000000..d75fc2c --- /dev/null +++ b/lib/screens/home_page.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import 'kasir_screen.dart'; +import 'produk_screen.dart'; +import 'riwayat_screen.dart'; +import 'pengaturan_screen.dart'; +import 'printer_screen.dart'; +import '../state/app_state.dart'; +import '../utils/colors.dart'; + +class HomePage extends StatefulWidget { + const HomePage({super.key}); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + int _index = 0; + + List _screensForRole(String? role) { + final screens = [const KasirScreen()]; + if (role == 'admin') { + screens.addAll([ + const ProdukScreen(), + const RiwayatScreen(), + const PengaturanScreen(), + ]); + } else { + screens.addAll([ + const RiwayatScreen(), + const PrinterScreen(), + ]); + } + return screens; + } + + List _navItemsForRole(String? role) { + final items = [ + const BottomNavigationBarItem( + icon: Icon(Icons.point_of_sale), + label: 'Kasir', + ), + ]; + if (role == 'admin') { + items.addAll([ + const BottomNavigationBarItem( + icon: Icon(Icons.inventory_2), + label: 'Produk', + ), + const BottomNavigationBarItem( + icon: Icon(Icons.receipt_long), + label: 'Riwayat', + ), + const BottomNavigationBarItem( + icon: Icon(Icons.settings_outlined), + label: 'Pengaturan', + ), + ]); + } else { + items.addAll([ + const BottomNavigationBarItem( + icon: Icon(Icons.receipt_long), + label: 'Riwayat', + ), + const BottomNavigationBarItem( + icon: Icon(Icons.print_outlined), + label: 'Printer', + ), + ]); + } + return items; + } + + @override + Widget build(BuildContext context) { + final state = context.watch(); + final screens = _screensForRole(state.userRole); + final navItems = _navItemsForRole(state.userRole); + + final safeIndex = _index >= screens.length ? 0 : _index; + + return Scaffold( + appBar: AppBar( + title: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.storefront_rounded, color: kAccent), + const SizedBox(width: 8), + const Text('Dutra Store'), + ], + ), + centerTitle: true, + elevation: 0, + actions: [ + IconButton( + icon: const Icon(Icons.logout, color: kMuted), + onPressed: () async { + await context.read().logout(); + }, + tooltip: 'Logout', + ), + ], + ), + body: IndexedStack( + index: safeIndex, + children: screens, + ), + bottomNavigationBar: navItems.length >= 2 + ? BottomNavigationBar( + currentIndex: safeIndex, + onTap: (i) => setState(() => _index = i), + items: navItems, + ) + : null, + ); + } +} + diff --git a/lib/screens/kasir_screen.dart b/lib/screens/kasir_screen.dart new file mode 100644 index 0000000..c2271cd --- /dev/null +++ b/lib/screens/kasir_screen.dart @@ -0,0 +1,1450 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'dart:async'; + +import '../models/product.dart'; +import '../models/sale.dart'; +import '../state/app_state.dart'; +import '../services/printer_service.dart'; +import '../utils/colors.dart'; +import '../utils/format.dart'; +import '../utils/rupiah_input.dart'; + +class KasirScreen extends StatefulWidget { + const KasirScreen({super.key}); + + @override + State createState() => _KasirScreenState(); +} + +class _KasirScreenState extends State { + final TextEditingController _search = TextEditingController(); + Timer? _searchDebounce; + + @override + void dispose() { + _searchDebounce?.cancel(); + _search.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final state = context.watch(); + if (state.loading) { + return const Center(child: CircularProgressIndicator(color: kAccent)); + } + final query = _search.text.toLowerCase(); + final isReseller = state.customerType == 'reseller'; + final products = state.products + .where((p) => + p.name.toLowerCase().contains(query) || + p.barcode.toLowerCase().contains(query)) + .toList(); + + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 6), + child: TextField( + controller: _search, + onChanged: (_) { + _searchDebounce?.cancel(); + _searchDebounce = Timer(const Duration(milliseconds: 300), () { + if (mounted) setState(() {}); + }); + }, + style: const TextStyle(color: kText), + decoration: InputDecoration( + hintText: 'Cari produk...', + prefixIcon: const Icon(Icons.search, color: kMuted), + suffixIcon: _search.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.close, color: kMuted), + onPressed: () { + _search.clear(); + setState(() {}); + }, + ) + : null, + ), + ), + ), + if (state.resellerEnabled) Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 6), + child: Row( + children: [ + const Text('Pembeli:', + style: TextStyle(color: kMuted, fontSize: 13)), + const SizedBox(width: 10), + Expanded( + child: SegmentedButton( + segments: const [ + ButtonSegment(value: 'umum', label: Text('Umum')), + ButtonSegment( + value: 'reseller', label: Text('Reseller')), + ], + selected: {state.customerType}, + onSelectionChanged: (set) => + state.setCustomerType(set.first), + style: SegmentedButton.styleFrom( + visualDensity: VisualDensity.compact, + ), + ), + ), + ], + ), + ), + Expanded( + child: products.isEmpty + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon(Icons.search_off, size: 48, color: kMuted), + SizedBox(height: 8), + Text('Produk tidak ditemukan', + style: TextStyle(color: kMuted)), + ], + ), + ) + : RefreshIndicator( + onRefresh: () async { + context.read().recordManualRefresh(); + await context.read().refresh(); + }, + color: kAccent, + child: GridView.builder( + padding: const EdgeInsets.fromLTRB(12, 6, 12, 12), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisSpacing: 12, + crossAxisSpacing: 12, + childAspectRatio: 1.1, + ), + itemCount: products.length, + itemBuilder: (context, i) => _ProductCard( + product: products[i], + displayPrice: + isReseller ? products[i].priceReseller : products[i].price, + isReseller: isReseller, + onTap: () { + HapticFeedback.lightImpact(); + state.addToCart(products[i]); + }, + ), + ), + ), + ), + if (state.cart.isNotEmpty) + _CartBar( + onTap: () => _openCartSheet(context, state), + itemCount: state.cart.fold(0, (s, c) => s + c.qty), + ), + ], + ); + } + + void _openCartSheet(BuildContext context, AppState state) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) => DraggableScrollableSheet( + initialChildSize: 0.6, + minChildSize: 0.35, + maxChildSize: 0.92, + builder: (_, controller) => Container( + decoration: const BoxDecoration( + color: kSurface, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + border: Border(top: BorderSide(color: kBorder)), + ), + child: _CartSheetContent( + scrollController: controller, + onPay: () => _showPaymentDialog(sheetContext, state), + ), + ), + ), + ); + } + + void _showPaymentDialog(BuildContext sheetContext, AppState state) { + final paidCtrl = TextEditingController(); + double change = 0; + final total = state.total; + String paymentMethod = 'tunai'; + final Map splitPayment = {}; + + showDialog( + context: sheetContext, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setDialog) { + final isPayingRef = [false]; + DateTime? payingStart; + final messenger = ScaffoldMessenger.of(context); + + void updatePaid(String v) { + if (isPayingRef[0]) return; + final paid = (RupiahInputFormatter.getRawValue(v) ?? 0).toDouble(); + setDialog(() { + change = paid - total; + }); + } + + Future handlePay() async { + if (isPayingRef[0]) return; + final paid = + (RupiahInputFormatter.getRawValue(paidCtrl.text) ?? 0) + .toDouble(); + if (paymentMethod == 'tunai' && paid < total) { + messenger.showSnackBar( + const SnackBar( + content: Text('Uang dibayar kurang dari total'), + backgroundColor: kDanger, + ), + ); + return; + } + payingStart = DateTime.now(); + setDialog(() => isPayingRef[0] = true); + try { + final isBayarNanti = paymentMethod == 'bayar_nanti'; + final sale = await state.checkout( + isBayarNanti ? 0 : paid, + paymentMethod: isBayarNanti ? 'tunai' : paymentMethod, + splitPayment: paymentMethod == 'split' && splitPayment.isNotEmpty + ? Map.from(splitPayment) + : null, + paymentStatus: isBayarNanti ? 'unpaid' : 'paid', + dueAmount: isBayarNanti ? total : 0.0, + ); + if (!dialogContext.mounted) return; + final elapsed = DateTime.now().difference(payingStart!); + if (elapsed < const Duration(milliseconds: 300)) { + await Future.delayed(const Duration(milliseconds: 300) - elapsed); + } + if (!dialogContext.mounted) return; + Navigator.pop(dialogContext); + Navigator.pop(sheetContext); + if (mounted) { + HapticFeedback.mediumImpact(); + _showReceipt(dialogContext, sale); + } + } catch (e) { + if (!dialogContext.mounted) return; + Navigator.pop(dialogContext); + Navigator.pop(sheetContext); + messenger.showSnackBar( + const SnackBar( + content: Text( + 'Transaksi disimpan offline dan akan disinkronkan saat koneksi kembali'), + backgroundColor: kSuccess, + duration: Duration(seconds: 3), + ), + ); + } finally { + if (dialogContext.mounted) { + setDialog(() => isPayingRef[0] = false); + } + } + } + + return AlertDialog( + contentPadding: const EdgeInsets.all(20), + content: SizedBox( + width: double.maxFinite, + child: Stack( + children: [ + SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + const Icon(Icons.payments_outlined, color: kAccent), + const SizedBox(width: 8), + const Text('Pembayaran', + style: TextStyle( + fontSize: 18, fontWeight: FontWeight.w700)), + const Spacer(), + IconButton( + icon: const Icon(Icons.close, color: kMuted), + onPressed: isPayingRef[0] + ? null + : () => Navigator.pop(dialogContext), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + const SizedBox(height: 16), + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(14), + ), + child: Column( + children: [ + const Text('TOTAL BELANJA', + style: TextStyle( + fontSize: 11, + color: kMuted, + letterSpacing: 1)), + const SizedBox(height: 4), + Text(formatRupiah(total), + style: const TextStyle( + fontSize: 26, + fontWeight: FontWeight.w800, + color: kAccent)), + ], + ), + ), + const SizedBox(height: 16), + const Align( + alignment: Alignment.centerLeft, + child: Text('Metode Pembayaran', + style: TextStyle( + fontSize: 13, fontWeight: FontWeight.w600)), + ), + const SizedBox(height: 8), + Column( + children: [ + Row( + children: [ + Expanded( + child: _PaymentMethodChip( + label: 'Tunai', + icon: Icons.money_outlined, + selected: paymentMethod == 'tunai', + onTap: isPayingRef[0] + ? null + : () => setDialog(() => paymentMethod = 'tunai'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _PaymentMethodChip( + label: 'Bank', + icon: Icons.account_balance_outlined, + selected: paymentMethod == 'transfer', + onTap: isPayingRef[0] + ? null + : () => setDialog(() => paymentMethod = 'transfer'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _PaymentMethodChip( + label: 'QRIS', + icon: Icons.qr_code_2_outlined, + selected: paymentMethod == 'qris', + onTap: isPayingRef[0] + ? null + : () => setDialog(() => paymentMethod = 'qris'), + ), + ), + ], + ), + const SizedBox(height: 8), + const Divider(height: 1, thickness: 1), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: _PaymentMethodChip( + label: 'Bayar Nanti', + icon: Icons.watch_later_outlined, + selected: paymentMethod == 'bayar_nanti', + onTap: isPayingRef[0] + ? null + : () => setDialog(() => paymentMethod = 'bayar_nanti'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: _PaymentMethodChip( + label: 'Split', + icon: Icons.call_split_outlined, + selected: paymentMethod == 'split', + onTap: isPayingRef[0] + ? null + : () => setDialog(() => paymentMethod = 'split'), + ), + ), + ], + ), + ], + ), + const SizedBox(height: 16), + if (paymentMethod == 'tunai' || paymentMethod == 'bayar_nanti') ...[ + AbsorbPointer( + absorbing: isPayingRef[0] || paymentMethod == 'bayar_nanti', + child: TextField( + controller: paidCtrl, + keyboardType: TextInputType.number, + inputFormatters: paymentMethod == 'bayar_nanti' ? [] : [RupiahInputFormatter()], + style: const TextStyle( + fontSize: 18, fontWeight: FontWeight.w600), + decoration: InputDecoration( + labelText: paymentMethod == 'bayar_nanti' ? 'Belum Bayar' : 'Uang Dibayar', + prefixText: 'Rp ', + helperText: paymentMethod == 'bayar_nanti' ? 'Pembayaran dilakukan saat customer datang' : null, + ), + onChanged: paymentMethod == 'bayar_nanti' ? null : updatePaid, + ), + ), + const SizedBox(height: 10), + AbsorbPointer( + absorbing: isPayingRef[0], + child: Wrap( + spacing: 8, + runSpacing: 8, + children: [ + _Chip('Uang Pas', () { + paidCtrl.text = + RupiahInputFormatter.formatNumber(total.round()); + updatePaid(paidCtrl.text); + }), + _Chip('+5rb', () { + final current = + RupiahInputFormatter.getRawValue(paidCtrl.text) ?? 0; + paidCtrl.text = + RupiahInputFormatter.formatNumber(current + 5000); + updatePaid(paidCtrl.text); + }), + _Chip('+10rb', () { + final current = + RupiahInputFormatter.getRawValue(paidCtrl.text) ?? 0; + paidCtrl.text = + RupiahInputFormatter.formatNumber(current + 10000); + updatePaid(paidCtrl.text); + }), + _Chip('+20rb', () { + final current = + RupiahInputFormatter.getRawValue(paidCtrl.text) ?? 0; + paidCtrl.text = + RupiahInputFormatter.formatNumber(current + 20000); + updatePaid(paidCtrl.text); + }), + _Chip('+50rb', () { + final current = + RupiahInputFormatter.getRawValue(paidCtrl.text) ?? 0; + paidCtrl.text = + RupiahInputFormatter.formatNumber(current + 50000); + updatePaid(paidCtrl.text); + }), + _Chip('+100rb', () { + final current = + RupiahInputFormatter.getRawValue(paidCtrl.text) ?? 0; + paidCtrl.text = + RupiahInputFormatter.formatNumber(current + 100000); + updatePaid(paidCtrl.text); + }), + ], + ), + ), + const SizedBox(height: 16), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: paymentMethod == 'bayar_nanti' + ? kMuted.withValues(alpha: 0.12) + : change >= 0 + ? kSuccess.withValues(alpha: 0.12) + : kDanger.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(paymentMethod == 'bayar_nanti' ? 'Status' : 'Kembalian', + style: const TextStyle(color: kMuted)), + Text( + paymentMethod == 'bayar_nanti' + ? 'Belum Bayar' + : formatRupiah(change > 0 ? change : 0), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: paymentMethod == 'bayar_nanti' + ? kMuted + : change >= 0 + ? kSuccess + : kDanger, + ), + ), + ], + ), + ), + ] else if (paymentMethod == 'split') ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Pembayaran Gabungan', + style: TextStyle( + fontSize: 13, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + ...['tunai', 'transfer', 'qris'].map((method) { + final label = method == 'tunai' + ? 'Tunai' + : method == 'transfer' + ? 'Bank' + : 'QRIS'; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Expanded( + child: Text(label, + style: const TextStyle(fontSize: 13)), + ), + SizedBox( + width: 120, + child: TextField( + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: InputDecoration( + labelText: 'Rp $label', + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 8), + ), + onChanged: (v) { + final raw = RupiahInputFormatter.getRawValue(v) ?? 0; + setDialog(() { + if (raw > 0) { + splitPayment[method] = raw.toDouble(); + } else { + splitPayment.remove(method); + } + }); + }, + ), + ), + ], + ), + ); + }), + const SizedBox(height: 8), + Text( + 'Total split: ${formatRupiah(splitPayment.values.fold(0.0, (s, v) => s + v))} / ${formatRupiah(total)}', + style: TextStyle( + fontSize: 12, + color: splitPayment.values.fold(0.0, (s, v) => s + v) >= total + ? kSuccess + : kDanger, + ), + ), + ], + ), + ), + ] else ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + paymentMethod == 'transfer' + ? 'Transfer ke rekening toko. Konfirmasi pembayaran sebelum lanjut.' + : 'Tampilkan kode QRIS ke customer untuk scan.', + style: const TextStyle(fontSize: 13, color: kMuted), + ), + ), + const SizedBox(height: 12), + AbsorbPointer( + absorbing: isPayingRef[0], + child: TextField( + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + style: const TextStyle( + fontSize: 18, fontWeight: FontWeight.w600), + decoration: InputDecoration( + labelText: paymentMethod == 'transfer' + ? 'Jumlah Bank' + : 'Jumlah QRIS', + prefixText: 'Rp ', + ), + onChanged: (v) { + final paid = (RupiahInputFormatter.getRawValue(v) ?? 0).toDouble(); + setDialog(() { + change = paid - total; + }); + }, + ), + ), + const SizedBox(height: 16), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: change >= 0 + ? kSuccess.withValues(alpha: 0.12) + : kDanger.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Status', + style: TextStyle(color: kMuted)), + Text( + change >= 0 ? 'Lunas' : 'Kurang ${formatRupiah(change.abs())}', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: change >= 0 ? kSuccess : kDanger, + ), + ), + ], + ), + ), + ], + const SizedBox(height: 18), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: isPayingRef[0] ? null : handlePay, + style: FilledButton.styleFrom( + backgroundColor: kSuccess, + foregroundColor: const Color(0xFF06210F), + ), + child: isPayingRef[0] + ? const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Color(0xFF06210F), + ), + ), + SizedBox(width: 10), + Text('Memproses...', + style: TextStyle( + fontWeight: FontWeight.w700)), + ], + ) + : Text(paymentMethod == 'bayar_nanti' ? 'Pesanan Sekarang' : paymentMethod == 'tunai' ? 'Selesai & Cetak' : 'Selesai'), + ), + ), + ], + ), + ), + ], + ), + ), + ); + }, + ); + }, + ); + } + + void _showReceipt(BuildContext context, Sale sale) { + showDialog( + context: context, + builder: (context) { + return AlertDialog( + contentPadding: const EdgeInsets.all(20), + content: SizedBox( + width: double.maxFinite, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircleAvatar( + radius: 26, + backgroundColor: kSuccess, + child: Icon(Icons.check, color: Colors.white, size: 30), + ), + const SizedBox(height: 10), + const Text('Pembayaran Berhasil', + style: + TextStyle(fontSize: 18, fontWeight: FontWeight.w700)), + const SizedBox(height: 2), + Text( + '${formatTanggal(sale.date)} ${formatWaktu(sale.date)}', + style: const TextStyle(color: kMuted, fontSize: 12), + ), + const SizedBox(height: 4), + Text('#${sale.id.toUpperCase()}', + style: const TextStyle(color: kMuted, fontSize: 11)), + const Divider(height: 24), + ...sale.items.map((it) => Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text('${it.name} x${it.qty}', + style: const TextStyle(fontSize: 14)), + ), + Text(formatRupiah(it.subtotal), + style: const TextStyle( + fontSize: 14, fontWeight: FontWeight.w600)), + ], + ), + const SizedBox(height: 2), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 1), + decoration: BoxDecoration( + color: it.isReseller + ? kAccent.withValues(alpha: 0.15) + : kMuted.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + it.isReseller ? 'Reseller' : 'Umum', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: it.isReseller ? kAccent : kMuted, + ), + ), + ), + ], + ), + )), + const SizedBox(height: 4), + Text( + 'Kasir: ${context.read().getProfileName(sale.userId)}', + style: const TextStyle(color: kMuted, fontSize: 12), + ), + if (sale.discount > 0) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Diskon', + style: TextStyle(color: kMuted)), + Text('-${formatRupiah(sale.discount)}', + style: const TextStyle(color: kMuted)), + ], + ), + ), + const Divider(height: 24), + _ReceiptRow('Total', formatRupiah(sale.total), true), + _ReceiptRow('Metode', _paymentMethodLabel(sale.paymentMethod), false), + if (sale.paymentStatus == 'unpaid') ...[ + _ReceiptRow('Status', 'Belum Lunas', false), + _ReceiptRow('Sisa', formatRupiah(sale.dueAmount), false), + ] else if (sale.paymentMethod == 'tunai') ...[ + _ReceiptRow('Bayar', formatRupiah(sale.paid), false), + _ReceiptRow('Kembali', formatRupiah(sale.change), false), + ], + if (sale.splitPayment != null && sale.splitPayment!.isNotEmpty) + ...sale.splitPayment!.entries.map((e) { + final label = e.key == 'tunai' + ? 'Tunai' + : e.key == 'transfer' + ? 'Bank' + : 'QRIS'; + return _ReceiptRow('Split $label', formatRupiah(e.value), false); + }), + const SizedBox(height: 16), + const Text('Terima kasih!', + style: TextStyle(color: kMuted)), + ], + ), + ), + actions: [ + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => Navigator.pop(context), + child: const Text('Tutup'), + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: () async { + HapticFeedback.lightImpact(); + final messenger = ScaffoldMessenger.of(context); + final prefs = await SharedPreferences.getInstance(); + final storeName = + prefs.getString('store_name') ?? 'Toko Grosir'; + final err = await printerService.printSale( + sale, + storeName, + kasirName: context.read().getProfileName(sale.userId), + whatsapp: prefs.getString('store_whatsapp'), + notes: prefs.getString('store_notes'), + ); + if (mounted) { + messenger.showSnackBar( + SnackBar( + content: Text(err == null + ? 'Struk dikirim ke printer' + : 'Gagal cetak: $err'), + backgroundColor: err == null ? kSuccess : kDanger, + ), + ); + } + }, + icon: const Icon(Icons.print_outlined), + label: const Text('Cetak Struk'), + ), + ), + ], + ); + }, + ); + } +} + +class _CartBar extends StatefulWidget { + final VoidCallback onTap; + final int itemCount; + const _CartBar({required this.onTap, required this.itemCount}); + + @override + State<_CartBar> createState() => _CartBarState(); +} + +class _CartBarState extends State<_CartBar> + with SingleTickerProviderStateMixin { + late AnimationController _controller; + late Animation _scaleAnim; + + @override + void initState() { + super.initState(); + _controller = AnimationController( + duration: const Duration(milliseconds: 180), + vsync: this, + ); + _scaleAnim = Tween(begin: 1.0, end: 0.9).animate( + CurvedAnimation(parent: _controller, curve: Curves.easeInOut), + ); + } + + @override + void didUpdateWidget(covariant _CartBar oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.itemCount > oldWidget.itemCount) { + _controller.forward().then((_) => _controller.reverse()); + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final state = context.watch(); + + return Material( + color: kSurface, + child: InkWell( + onTap: widget.onTap, + child: ScaleTransition( + scale: _scaleAnim, + child: Container( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + decoration: const BoxDecoration( + border: Border(top: BorderSide(color: kBorder)), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: kAccent.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.shopping_cart_outlined, color: kAccent, size: 20), + ), + const SizedBox(width: 10), + Text('${widget.itemCount} item', + style: const TextStyle( + fontWeight: FontWeight.w700, fontSize: 15)), + const Spacer(), + Text(formatRupiah(state.total), + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.w800, + color: kAccent)), + const SizedBox(width: 8), + Icon(Icons.expand_less, color: kMuted.withValues(alpha: 0.7)), + ], + ), + ), + ), + ), + ); + } +} + +class _CartSheetContent extends StatelessWidget { + final ScrollController scrollController; + final VoidCallback onPay; + const _CartSheetContent( + {required this.scrollController, required this.onPay}); + + @override + Widget build(BuildContext context) { + final state = context.watch(); + final items = state.cart; + + final children = [ + Container( + margin: const EdgeInsets.only(top: 12), + width: 40, + height: 4, + decoration: BoxDecoration( + color: kBorder, + borderRadius: BorderRadius.circular(4), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + children: [ + const Icon(Icons.shopping_cart_outlined, color: kAccent), + const SizedBox(width: 8), + const Text('Keranjang', + style: TextStyle(fontWeight: FontWeight.w700, fontSize: 17)), + const Spacer(), + if (items.isNotEmpty) + OutlinedButton( + onPressed: () async { + final confirm = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + icon: Icon(Icons.delete_forever_outlined, color: kDanger, size: 28), + title: const Text('Kosongkan Keranjang?'), + content: const Text( + 'Semua item di keranjang akan dihapus. Tindakan ini tidak dapat dibatalkan.', + ), + actions: [ + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () => Navigator.pop(ctx, false), + style: OutlinedButton.styleFrom( + foregroundColor: kMuted, + side: const BorderSide(color: kBorder), + ), + child: const Text('Batal'), + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => Navigator.pop(ctx, true), + style: FilledButton.styleFrom( + backgroundColor: kDanger, + ), + child: const Text('Kosongkan'), + ), + ), + ], + ), + ); + if (confirm == true && context.mounted) { + state.clearCart(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Keranjang dikosongkan'), + backgroundColor: kSuccess, + ), + ); + } + }, + style: OutlinedButton.styleFrom( + foregroundColor: kDanger, + side: const BorderSide(color: kDanger), + ), + child: const Text('Kosongkan'), + ), + ], + ), + ), + const Divider(height: 12), + ]; + + if (items.isEmpty) { + children.add(Padding( + padding: const EdgeInsets.symmetric(vertical: 40), + child: Center( + child: Column( + children: [ + Icon(Icons.shopping_cart_outlined, size: 48, color: kMuted), + const SizedBox(height: 12), + Text('Keranjang kosong', style: TextStyle(color: kMuted)), + ], + ), + ), + )); + } else { + for (var i = 0; i < items.length; i++) { + final line = items[i]; + children.add(Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + child: Row( + children: [ + CircleAvatar( + radius: 18, + backgroundColor: kAccent.withValues(alpha: 0.15), + child: Text( + line.product.name.isNotEmpty + ? line.product.name[0].toUpperCase() + : '?', + style: TextStyle( + color: kAccent, + fontWeight: FontWeight.w700, + fontSize: 13), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(line.product.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, fontWeight: FontWeight.w600)), + const SizedBox(height: 2), + Text( + '${formatRupiah(line.price)} /pcs', + style: const TextStyle(fontSize: 11, color: kMuted), + ), + ], + ), + ), + if (state.resellerEnabled) InkWell( + onTap: () => state.toggleLineMode(line.product.id), + borderRadius: BorderRadius.circular(8), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: line.isReseller + ? kAccent.withValues(alpha: 0.15) + : kSurface2, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: line.isReseller ? kAccent : kBorder, + ), + ), + child: Text( + line.isReseller ? 'Reseller' : 'Umum', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: line.isReseller ? kAccent : kMuted), + ), + ), + ), + const SizedBox(width: 8), + Container( + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: kBorder), + ), + child: Row( + children: [ + _QtyButton( + icon: Icons.remove, + onTap: () => state.changeQty(line.product.id, -1), + ), + SizedBox( + width: 32, + child: Text('${line.qty}', + textAlign: TextAlign.center, + style: + const TextStyle(fontWeight: FontWeight.w700)), + ), + _QtyButton( + icon: Icons.add, + onTap: () => state.changeQty(line.product.id, 1), + ), + ], + ), + ), + ], + ), + )); + if (i < items.length - 1) { + children.add(const Divider(height: 1, indent: 16, endIndent: 16)); + } + } + + children.add(const SizedBox(height: 12)); + children.add(Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Subtotal', style: TextStyle(color: kMuted)), + Text(formatRupiah(state.subtotal), + style: const TextStyle(fontWeight: FontWeight.w600)), + ], + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Diskon', style: TextStyle(color: kMuted)), + SizedBox( + width: 140, + child: TextField( + keyboardType: TextInputType.number, + textAlign: TextAlign.right, + inputFormatters: [RupiahInputFormatter()], + style: const TextStyle(fontSize: 14), + onChanged: (v) => + state.setDiscount((RupiahInputFormatter.getRawValue(v) ?? 0).toDouble()), + decoration: const InputDecoration( + isDense: true, + prefixText: 'Rp ', + contentPadding: EdgeInsets.symmetric(horizontal: 10), + ), + ), + ), + ], + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Total', + style: + TextStyle(fontSize: 16, fontWeight: FontWeight.w800)), + Text(formatRupiah(state.total), + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w800, + color: kAccent)), + ], + ), + const SizedBox(height: 14), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: state.canCheckout ? onPay : null, + icon: const Icon(Icons.point_of_sale), + label: const Text('Bayar'), + style: FilledButton.styleFrom( + backgroundColor: kSuccess, + foregroundColor: const Color(0xFF06210F), + ), + ), + ), + ], + ), + )); + } + + return SingleChildScrollView( + controller: scrollController, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ); + } +} + +class _Chip extends StatelessWidget { + final String label; + final VoidCallback onTap; + const _Chip(this.label, this.onTap); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: kBorder), + ), + child: Text(label, + style: const TextStyle( + color: kAccent, fontWeight: FontWeight.w600, fontSize: 13)), + ), + ); + } +} + +class _PaymentMethodChip extends StatelessWidget { + final String label; + final IconData icon; + final bool selected; + final VoidCallback? onTap; + const _PaymentMethodChip({ + required this.label, + required this.icon, + required this.selected, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: AnimatedContainer( + duration: const Duration(milliseconds: 180), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14), + decoration: BoxDecoration( + color: selected ? kAccent.withValues(alpha: 0.18) : kSurface2, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: selected ? kAccent : kBorder, + width: selected ? 1.8 : 1, + ), + ), + child: Column( + children: [ + Icon(icon, + size: 22, + color: selected ? kAccent : kMuted), + const SizedBox(height: 6), + Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: selected ? FontWeight.w700 : FontWeight.w500, + color: selected ? kAccent : kText, + ), + ), + ], + ), + ), + ); + } +} + +String _paymentMethodLabel(String method) { + switch (method) { + case 'transfer': + return 'Bank'; + case 'qris': + return 'QRIS'; + case 'split': + return 'Split Payment'; + default: + return 'Tunai'; + } +} + +class _ReceiptRow extends StatelessWidget { + final String label; + final String value; + final bool bold; + const _ReceiptRow(this.label, this.value, this.bold); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label, + style: TextStyle( + color: bold ? kText : kMuted, + fontWeight: bold ? FontWeight.w700 : FontWeight.normal)), + Text(value, + style: TextStyle( + fontSize: bold ? 17 : 14, + fontWeight: bold ? FontWeight.w800 : FontWeight.w600, + color: bold ? kAccent : kText, + )), + ], + ), + ); + } +} + +class _ProductCard extends StatelessWidget { + final Product product; + final double displayPrice; + final bool isReseller; + final VoidCallback onTap; + const _ProductCard({ + required this.product, + required this.displayPrice, + required this.isReseller, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final out = product.stock <= 0; + + return AbsorbPointer( + absorbing: out, + child: Opacity( + opacity: out ? 0.5 : 1, + child: InkWell( + onTap: out ? null : onTap, + borderRadius: BorderRadius.circular(kRadius), + child: Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(kRadius), + border: Border.all(color: kBorder), + boxShadow: const [ + BoxShadow( + color: Colors.black26, + blurRadius: 8, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 18, + backgroundColor: kAccent.withValues(alpha: 0.15), + child: Text( + product.name.isNotEmpty + ? product.name[0].toUpperCase() + : '?', + style: TextStyle( + color: kAccent, + fontWeight: FontWeight.w700, + ), + ), + ), + const Spacer(), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: out + ? kDanger.withValues(alpha: 0.15) + : kSuccess.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + out ? 'Habis' : 'Stok ${product.stock}', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: out ? kDanger : kSuccess, + ), + ), + ), + ], + ), + const Spacer(), + Text( + product.name, + style: const TextStyle( + fontWeight: FontWeight.w600, fontSize: 14), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + Wrap( + spacing: 6, + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 5), + decoration: BoxDecoration( + color: kAccent.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + formatRupiah(displayPrice), + style: TextStyle( + color: kAccent, + fontWeight: FontWeight.w800, + fontSize: 13, + ), + ), + ), + if (isReseller) ...[ + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: kAccent.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(6), + ), + child: const Text('Reseller', + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.w700, + color: kAccent)), + ), + ], + ], + ), + ], + ), + ), + ), + ), + ); + } +} + +class _QtyButton extends StatelessWidget { + final IconData icon; + final VoidCallback onTap; + const _QtyButton({required this.icon, required this.onTap}); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(22), + child: SizedBox( + width: 44, + height: 44, + child: Icon(icon, size: 20, color: kAccent), + ), + ); + } +} diff --git a/lib/screens/kelola_kasir_screen.dart b/lib/screens/kelola_kasir_screen.dart new file mode 100644 index 0000000..0645327 --- /dev/null +++ b/lib/screens/kelola_kasir_screen.dart @@ -0,0 +1,372 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../state/app_state.dart'; +import '../utils/colors.dart'; + +class KelolaKasirScreen extends StatefulWidget { + final bool embedded; + const KelolaKasirScreen({super.key, this.embedded = false}); + + @override + State createState() => _KelolaKasirScreenState(); +} + +class _KelolaKasirScreenState extends State { + final TextEditingController _emailCtrl = TextEditingController(); + final TextEditingController _passwordCtrl = TextEditingController(); + final TextEditingController _nameCtrl = TextEditingController(); + bool _loading = false; + String? _error; + + @override + void initState() { + super.initState(); + context.read().loadKasirAccounts(); + } + + @override + void dispose() { + _emailCtrl.dispose(); + _passwordCtrl.dispose(); + _nameCtrl.dispose(); + super.dispose(); + } + + Future _addKasir() async { + final email = _emailCtrl.text.trim(); + final password = _passwordCtrl.text; + final name = _nameCtrl.text.trim(); + + if (email.isEmpty || password.isEmpty) { + setState(() => _error = 'Email dan password harus diisi'); + return; + } + + setState(() { + _loading = true; + _error = null; + }); + + final state = context.read(); + final err = await state.createKasir(email, password, name); + if (mounted) { + setState(() => _loading = false); + if (err != null) { + setState(() => _error = err); + } else { + _emailCtrl.clear(); + _passwordCtrl.clear(); + _nameCtrl.clear(); + } + } + } + + @override + Widget build(BuildContext context) { + final body = _buildBody(context); + if (widget.embedded) return body; + return Scaffold( + appBar: AppBar( + title: const Text('Akun Kasir'), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: body, + ), + ); + } + + Widget _buildBody(BuildContext context) { + final state = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.person_add_outlined, color: kAccent), + const SizedBox(width: 8), + Text( + 'Tambah Akun Kasir', + style: TextStyle( + fontSize: 16, fontWeight: FontWeight.w700, color: kText), + ), + ], + ), + const SizedBox(height: 14), + TextField( + controller: _nameCtrl, + decoration: const InputDecoration( + labelText: 'Nama Lengkap', + prefixIcon: Icon(Icons.person_outline), + ), + ), + const SizedBox(height: 10), + TextField( + controller: _emailCtrl, + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: 'Email', + prefixIcon: Icon(Icons.email_outlined), + ), + ), + const SizedBox(height: 10), + TextField( + controller: _passwordCtrl, + obscureText: true, + decoration: const InputDecoration( + labelText: 'Password', + prefixIcon: Icon(Icons.lock_outlined), + ), + ), + if (_error != null) ...[ + const SizedBox(height: 10), + Text(_error!, + style: const TextStyle(color: kDanger, fontSize: 13)), + ], + const SizedBox(height: 14), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: _loading ? null : _addKasir, + icon: _loading + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, color: Color(0xFF1A1206)), + ) + : const Icon(Icons.add), + label: Text(_loading ? 'Menyimpan...' : 'Tambah Kasir'), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 12), + Text( + 'Daftar Akun Kasir', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: kText), + ), + const SizedBox(height: 10), + if (state.kasirAccounts.isEmpty) + Center( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 40), + child: Column( + children: const [ + Icon(Icons.people_outline, size: 48, color: kMuted), + SizedBox(height: 8), + Text('Belum ada akun kasir', style: TextStyle(color: kMuted)), + ], + ), + ) + ) + else + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: state.kasirAccounts.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, i) { + final kasir = state.kasirAccounts[i]; + return Card( + child: ListTile( + leading: CircleAvatar( + backgroundColor: kAccent.withValues(alpha: 0.15), + child: Text( + (kasir['full_name']?.toString().isNotEmpty == true + ? kasir['full_name'].toString() + : kasir['email']?.toString()) + ?.isNotEmpty == + true + ? (kasir['full_name']?.toString().isNotEmpty == true + ? kasir['full_name'].toString() + : kasir['email'].toString())[0].toUpperCase() + : '?', + style: TextStyle(color: kAccent, fontWeight: FontWeight.w700), + ), + ), + title: Text( + (kasir['full_name']?.toString().isNotEmpty == true + ? kasir['full_name'].toString() + : kasir['email']?.toString().isNotEmpty == true + ? kasir['email'].toString() + : 'Tanpa Nama'), + style: const TextStyle(fontWeight: FontWeight.w600), + ), + subtitle: Text( + '${kasir['role'] == 'kasir' ? 'Kasir' : 'Admin'}${kasir['email']?.toString().isNotEmpty == true ? ' • ${kasir['email']}' : ''}', + style: const TextStyle(fontSize: 12, color: kMuted), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.edit_outlined, size: 20), + color: kAccent, + onPressed: () { + _showEditDialog(context, state, kasir); + }, + ), + IconButton( + icon: const Icon(Icons.delete_outline, size: 20), + color: kDanger, + onPressed: () async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + icon: Icon(Icons.person_remove_outlined, color: kDanger, size: 28), + title: const Text('Hapus Akun'), + content: Text( + 'Yakin ingin menghapus akun ${kasir['full_name']?.toString().isNotEmpty == true ? kasir['full_name'] : (kasir['email']?.toString().isNotEmpty == true ? kasir['email'] : '')}?'), + actions: [ + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () => Navigator.pop(context, false), + style: OutlinedButton.styleFrom( + foregroundColor: kMuted, + side: const BorderSide(color: kBorder), + ), + child: const Text('Batal'), + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => Navigator.pop(context, true), + style: FilledButton.styleFrom( + backgroundColor: kDanger, + ), + child: const Text('Hapus'), + ), + ), + ], + ), + ); + if (confirm == true && mounted) { + await state.deleteKasir(kasir['id'].toString()); + } + }, + ), + ], + ), + ), + ); + }, + ), + ], + ); + } + + void _showEditDialog(BuildContext context, AppState state, Map kasir) { + final emailCtrl = TextEditingController(text: kasir['email']?.toString() ?? ''); + final nameCtrl = TextEditingController(text: kasir['full_name']?.toString() ?? ''); + final passwordCtrl = TextEditingController(); + bool isLoading = false; + String? error; + + showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (ctx, setDialog) { + Future submit() async { + final email = emailCtrl.text.trim(); + final name = nameCtrl.text.trim(); + final password = passwordCtrl.text; + if (email.isEmpty) { + setDialog(() => error = 'Email harus diisi'); + return; + } + setDialog(() { + isLoading = true; + error = null; + }); + final err = await state.updateKasir( + kasir['id'].toString(), + email, + name, + password.isEmpty ? null : password, + ); + if (!dialogContext.mounted) return; + setDialog(() => isLoading = false); + if (err != null) { + setDialog(() => error = err); + } else { + Navigator.pop(dialogContext); + } + } + + return AlertDialog( + title: const Text('Edit Akun Kasir'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: emailCtrl, + keyboardType: TextInputType.emailAddress, + decoration: const InputDecoration( + labelText: 'Email', + prefixIcon: Icon(Icons.email_outlined), + ), + ), + const SizedBox(height: 10), + TextField( + controller: nameCtrl, + decoration: const InputDecoration( + labelText: 'Nama Lengkap', + prefixIcon: Icon(Icons.person_outline), + ), + ), + const SizedBox(height: 10), + TextField( + controller: passwordCtrl, + obscureText: true, + decoration: const InputDecoration( + labelText: 'Password (kosongkan jika tidak diubah)', + prefixIcon: Icon(Icons.lock_outlined), + ), + ), + if (error != null) ...[ + const SizedBox(height: 10), + Text(error!, style: const TextStyle(color: kDanger, fontSize: 13)), + ], + ], + ), + actions: [ + TextButton( + onPressed: isLoading ? null : () => Navigator.pop(dialogContext), + child: const Text('Batal'), + ), + FilledButton( + onPressed: isLoading ? null : submit, + style: FilledButton.styleFrom(backgroundColor: kAccent), + child: isLoading + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, color: Color(0xFF1A1206)), + ) + : const Text('Simpan'), + ), + ], + ); + }, + ); + }, + ); + } +} + diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dart new file mode 100644 index 0000000..c6df471 --- /dev/null +++ b/lib/screens/login_screen.dart @@ -0,0 +1,135 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../state/app_state.dart'; +import '../utils/colors.dart'; + +class LoginScreen extends StatefulWidget { + const LoginScreen({super.key}); + + @override + State createState() => _LoginScreenState(); +} + +class _LoginScreenState extends State { + final _emailCtrl = TextEditingController(); + final _passwordCtrl = TextEditingController(); + String? _error; + bool _loading = false; + + @override + void dispose() { + _emailCtrl.dispose(); + _passwordCtrl.dispose(); + super.dispose(); + } + + Future _submit() async { + final email = _emailCtrl.text.trim(); + final password = _passwordCtrl.text; + if (email.isEmpty || password.isEmpty) { + setState(() => _error = 'Email dan password harus diisi'); + return; + } + setState(() { + _loading = true; + _error = null; + }); + final state = context.read(); + final err = await state.login(email, password); + if (mounted) { + setState(() => _loading = false); + if (err != null) { + setState(() => _error = err); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: SingleChildScrollView( + padding: EdgeInsets.only( + left: 24, + right: 24, + top: 24, + bottom: MediaQuery.of(context).viewInsets.bottom + 24, + ), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: Column( + children: [ + const SizedBox(height: 80), + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: kAccent.withValues(alpha: 0.15), + shape: BoxShape.circle, + ), + child: const Icon(Icons.storefront_rounded, + size: 48, color: kAccent), + ), + const SizedBox(height: 24), + Text( + 'Dutra Store', + style: TextStyle( + fontSize: 28, + fontWeight: FontWeight.w800, + color: kText, + ), + ), + const SizedBox(height: 8), + Text( + 'Masuk untuk melanjutkan', + style: TextStyle(color: kMuted, fontSize: 14), + ), + const SizedBox(height: 32), + TextField( + controller: _emailCtrl, + keyboardType: TextInputType.emailAddress, + style: const TextStyle(color: kText), + decoration: const InputDecoration( + labelText: 'Email', + prefixIcon: Icon(Icons.email_outlined, color: kMuted), + ), + ), + const SizedBox(height: 16), + TextField( + controller: _passwordCtrl, + obscureText: true, + style: const TextStyle(color: kText), + decoration: const InputDecoration( + labelText: 'Password', + prefixIcon: Icon(Icons.lock_outlined, color: kMuted), + ), + ), + if (_error != null) ...[ + const SizedBox(height: 12), + Text(_error!, + style: const TextStyle(color: kDanger, fontSize: 13)), + ], + const SizedBox(height: 24), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: _loading ? null : _submit, + child: _loading + ? const SizedBox( + height: 20, + width: 20, + child: CircularProgressIndicator( + strokeWidth: 2, color: Color(0xFF1A1206)), + ) + : const Text('Masuk'), + ), + ), + ], + ), + ), + ), + ), + ); + } +} + diff --git a/lib/screens/pengaturan_screen.dart b/lib/screens/pengaturan_screen.dart new file mode 100644 index 0000000..c525d4f --- /dev/null +++ b/lib/screens/pengaturan_screen.dart @@ -0,0 +1,262 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../state/app_state.dart'; +import '../utils/colors.dart'; +import 'kelola_kasir_screen.dart'; +import 'printer_screen.dart'; + +class PengaturanScreen extends StatefulWidget { + const PengaturanScreen({super.key}); + + @override + State createState() => _PengaturanScreenState(); +} + +class _PengaturanScreenState extends State { + final TextEditingController _storeNameCtrl = TextEditingController(); + final TextEditingController _currencyCtrl = TextEditingController(text: 'IDR'); + final TextEditingController _whatsappCtrl = TextEditingController(); + final TextEditingController _notesCtrl = TextEditingController(); + bool _resellerEnabled = true; + bool _loading = true; + + @override + void initState() { + super.initState(); + _loadSettings(); + } + + Future _loadSettings() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + _storeNameCtrl.text = prefs.getString('store_name') ?? 'Toko Grosir'; + _currencyCtrl.text = prefs.getString('currency') ?? 'IDR'; + _whatsappCtrl.text = prefs.getString('store_whatsapp') ?? ''; + _notesCtrl.text = prefs.getString('store_notes') ?? ''; + _resellerEnabled = prefs.getBool('reseller_enabled') ?? true; + _loading = false; + }); + } + + Future _saveSettings() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('store_name', _storeNameCtrl.text.trim()); + await prefs.setString('currency', _currencyCtrl.text.trim()); + await prefs.setString('store_whatsapp', _whatsappCtrl.text.trim()); + await prefs.setString('store_notes', _notesCtrl.text.trim()); + await prefs.setBool('reseller_enabled', _resellerEnabled); + if (!mounted) return; + final state = context.read(); + state.setResellerEnabled(_resellerEnabled); + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Center(child: CircularProgressIndicator(color: kAccent)); + } + + return RefreshIndicator( + onRefresh: () async { + context.read().recordManualRefresh(); + await context.read().refresh(); + }, + color: kAccent, + child: ListView( + padding: const EdgeInsets.all(12), + children: [ + _SettingsListTile( + icon: Icons.store_outlined, + title: 'Pengaturan Toko', + subtitle: _whatsappCtrl.text.isEmpty + ? '${_storeNameCtrl.text} • ${_currencyCtrl.text}' + : '${_storeNameCtrl.text} • ${_currencyCtrl.text} • ${_whatsappCtrl.text}', + onTap: () => _showStoreSettingsDialog(context), + ), + const SizedBox(height: 8), + _SettingsListTile( + icon: Icons.people_outline, + title: 'Akun Kasir', + subtitle: 'Tambah, edit, atau hapus akun kasir', + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const KelolaKasirScreen(), + ), + ); + }, + ), + const SizedBox(height: 8), + _SettingsListTile( + icon: Icons.print_outlined, + title: 'Printer Bluetooth', + subtitle: 'Scan, connect, dan cetak struk', + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const PrinterScreen(), + ), + ); + }, + ), + ], + ), + ); + } + + Future _showStoreSettingsDialog(BuildContext context) async { + final storeNameCtrl = TextEditingController(text: _storeNameCtrl.text); + final currencyCtrl = TextEditingController(text: _currencyCtrl.text); + final whatsappCtrl = TextEditingController(text: _whatsappCtrl.text); + final notesCtrl = TextEditingController(text: _notesCtrl.text); + bool resellerEnabled = _resellerEnabled; + + final messenger = ScaffoldMessenger.of(context); + + final result = await showDialog( + context: context, + builder: (ctx) => StatefulBuilder( + builder: (ctx, setModalState) => AlertDialog( + title: const Text('Pengaturan Toko'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: storeNameCtrl, + decoration: const InputDecoration( + labelText: 'Nama Toko', + prefixIcon: Icon(Icons.badge_outlined), + ), + ), + const SizedBox(height: 10), + TextField( + controller: currencyCtrl, + decoration: const InputDecoration( + labelText: 'Mata Uang', + prefixIcon: Icon(Icons.money_outlined), + ), + ), + const SizedBox(height: 10), + TextField( + controller: whatsappCtrl, + keyboardType: TextInputType.phone, + decoration: const InputDecoration( + labelText: 'No. WhatsApp', + prefixIcon: Icon(Icons.phone_outlined), + helperText: 'Contoh: 081234567890', + ), + ), + const SizedBox(height: 10), + TextField( + controller: notesCtrl, + maxLines: 3, + decoration: const InputDecoration( + labelText: 'Catatan Tambahan', + prefixIcon: Icon(Icons.notes_outlined), + helperText: 'Opsional, akan dicetak di struk', + ), + ), + const SizedBox(height: 10), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Mode Reseller Aktif', + style: TextStyle(fontSize: 14)), + subtitle: const Text( + 'Jika aktif, kasir bisa toggle harga reseller per transaksi', + style: TextStyle(fontSize: 12, color: kMuted)), + value: resellerEnabled, + onChanged: (v) => setModalState(() => resellerEnabled = v), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Batal'), + ), + FilledButton.icon( + onPressed: () async { + _storeNameCtrl.text = storeNameCtrl.text.trim(); + _currencyCtrl.text = currencyCtrl.text.trim(); + _whatsappCtrl.text = whatsappCtrl.text.trim(); + _notesCtrl.text = notesCtrl.text.trim(); + _resellerEnabled = resellerEnabled; + await _saveSettings(); + if (ctx.mounted) { + Navigator.pop(ctx, true); + } + }, + icon: const Icon(Icons.save_outlined, size: 18), + label: const Text('Simpan'), + ), + ], + ), + ), + ); + + if (result == true && mounted) { + messenger.showSnackBar( + const SnackBar( + content: Text('Pengaturan tersimpan'), + backgroundColor: kSuccess, + ), + ); + } + } + + @override + void dispose() { + _storeNameCtrl.dispose(); + _currencyCtrl.dispose(); + _whatsappCtrl.dispose(); + _notesCtrl.dispose(); + super.dispose(); + } +} + +class _SettingsListTile extends StatelessWidget { + final IconData icon; + final String title; + final String subtitle; + final VoidCallback onTap; + const _SettingsListTile({ + required this.icon, + required this.title, + required this.subtitle, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return Card( + child: ListTile( + leading: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: kAccent.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, color: kAccent, size: 20), + ), + title: Text( + title, + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w700), + ), + subtitle: Text( + subtitle, + style: const TextStyle(fontSize: 12, color: kMuted), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: Icon(Icons.chevron_right_rounded, color: kMuted, size: 20), + onTap: onTap, + ), + ); + } +} diff --git a/lib/screens/printer_screen.dart b/lib/screens/printer_screen.dart new file mode 100644 index 0000000..c5d2fec --- /dev/null +++ b/lib/screens/printer_screen.dart @@ -0,0 +1,279 @@ +import 'package:flutter/material.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; + +import '../services/printer_service.dart'; +import '../utils/colors.dart'; + +class PrinterScreen extends StatefulWidget { + final bool embedded; + const PrinterScreen({super.key, this.embedded = false}); + + @override + State createState() => _PrinterScreenState(); +} + +class _PrinterScreenState extends State { + List _devices = []; + bool _loading = false; + bool _scanning = false; + bool _connecting = false; + + @override + void initState() { + super.initState(); + _loadDevices(); + } + + Future _loadDevices() async { + setState(() => _loading = true); + try { + final enabled = await printerService.isBluetoothEnabled(); + if (!enabled) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Bluetooth belum aktif. Nyalakan Bluetooth di HP.'), + backgroundColor: kDanger, + ), + ); + } + } + _devices = await printerService.getPairedDevices(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Gagal memuat printer: $e')), + ); + } + } finally { + if (mounted) setState(() => _loading = false); + } + } + + Future _scan() async { + setState(() => _scanning = true); + try { + _devices = await printerService.getPairedDevices(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Gagal scan: $e')), + ); + } + } finally { + if (mounted) setState(() => _scanning = false); + } + } + + Future _connect(BluetoothInfo device) async { + setState(() => _connecting = true); + final ok = await printerService.connect(device.macAdress); + if (mounted) { + setState(() => _connecting = false); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(ok + ? 'Terhubung ke ${device.name}' + : 'Gagal hubungkan ${device.name}'), + backgroundColor: ok ? kSuccess : kDanger, + ), + ); + if (ok) setState(() {}); + } + } + + Future _disconnect() async { + await printerService.disconnect(); + if (mounted) setState(() {}); + } + + @override + Widget build(BuildContext context) { + final body = _buildBody(context); + if (widget.embedded) return body; + return Scaffold( + appBar: AppBar( + title: const Text('Printer Bluetooth'), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: body, + ), + ); + } + + Widget _buildBody(BuildContext context) { + final connected = printerService.isConnected; + final connectedMac = printerService.connectedMac; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + const Icon(Icons.print_outlined, color: kAccent), + const SizedBox(width: 8), + Text( + 'Printer Bluetooth', + style: TextStyle( + fontSize: 16, fontWeight: FontWeight.w700, color: kText), + ), + ], + ), + const SizedBox(height: 12), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: connected + ? kSuccess.withValues(alpha: 0.12) + : kSurface, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: connected ? kSuccess : kBorder, + ), + ), + child: Row( + children: [ + Icon( + connected ? Icons.bluetooth_connected : Icons.bluetooth, + color: connected ? kSuccess : kMuted, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + connected ? 'Terhubung' : 'Tidak terhubung', + style: TextStyle( + fontWeight: FontWeight.w600, + color: connected ? kSuccess : kMuted, + ), + ), + if (connected && connectedMac != null) + Text( + connectedMac, + style: const TextStyle( + fontSize: 12, color: kMuted), + ), + ], + ), + ), + if (connected) + TextButton( + onPressed: _connecting ? null : _disconnect, + child: const Text('Putus'), + ), + ], + ), + ), + const SizedBox(height: 14), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: _scanning ? null : _scan, + icon: _scanning + ? const SizedBox( + height: 16, + width: 16, + child: CircularProgressIndicator( + strokeWidth: 2, color: kAccent), + ) + : const Icon(Icons.refresh), + label: Text(_scanning ? 'Scanning...' : 'Scan Ulang'), + ), + ), + ], + ), + ], + ), + ), + ), + const SizedBox(height: 12), + Text( + 'Perangkat Tersedia', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: kText), + ), + const SizedBox(height: 10), + if (_loading) + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: CircularProgressIndicator(color: kAccent), + )) + else if (_devices.isEmpty) + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: Column( + children: [ + Icon(Icons.print_disabled_outlined, size: 48, color: kMuted), + SizedBox(height: 8), + Text('Tidak ada printer terpasang', + style: TextStyle(color: kMuted)), + SizedBox(height: 4), + Text('Pasangkan printer di pengaturan Bluetooth HP', + style: TextStyle(color: kMuted, fontSize: 12)), + ], + ), + ), + ) + else + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: _devices.length, + separatorBuilder: (_, __) => const SizedBox(height: 8), + itemBuilder: (context, i) { + final d = _devices[i]; + final isThis = connected && connectedMac == d.macAdress; + return Card( + child: ListTile( + leading: CircleAvatar( + backgroundColor: isThis + ? kSuccess.withValues(alpha: 0.15) + : kAccent.withValues(alpha: 0.15), + child: Icon( + isThis ? Icons.bluetooth_connected : Icons.print_outlined, + color: isThis ? kSuccess : kAccent, + ), + ), + title: Text(d.name.isNotEmpty ? d.name : 'Printer', + style: const TextStyle(fontWeight: FontWeight.w600)), + subtitle: Text(d.macAdress, + style: const TextStyle(fontSize: 12, color: kMuted)), + trailing: _connecting + ? const SizedBox( + height: 18, + width: 18, + child: CircularProgressIndicator( + strokeWidth: 2, color: kAccent), + ) + : isThis + ? const Chip( + label: Text('Aktif', + style: TextStyle(fontSize: 11)), + backgroundColor: kSuccess, + labelPadding: EdgeInsets.zero, + ) + : TextButton( + onPressed: () => _connect(d), + child: const Text('Hubungkan'), + ), + ), + ); + }, + ), + ], + ); + } +} + diff --git a/lib/screens/produk_screen.dart b/lib/screens/produk_screen.dart new file mode 100644 index 0000000..e6fff73 --- /dev/null +++ b/lib/screens/produk_screen.dart @@ -0,0 +1,802 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../models/product.dart'; +import '../state/app_state.dart'; +import '../utils/colors.dart'; +import '../utils/format.dart'; +import '../utils/rupiah_input.dart'; +import 'scan_screen.dart'; + +Future confirmResellerWarning(BuildContext context, double general, double reseller) async { + if (reseller <= 0 || reseller <= general) return true; + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + icon: Icon(Icons.warning_amber_rounded, color: kAccent, size: 28), + title: const Text('Peringatan'), + content: Text('Harga reseller (${formatRupiah(reseller)}) lebih tinggi dari harga umum (${formatRupiah(general)}).'), + actions: [ + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () => Navigator.pop(ctx, false), + style: OutlinedButton.styleFrom( + foregroundColor: kMuted, + side: const BorderSide(color: kBorder), + ), + child: const Text('Batal'), + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => Navigator.pop(ctx, true), + style: FilledButton.styleFrom(backgroundColor: kAccent), + child: const Text('Tetap Simpan'), + ), + ), + ], + ), + ); + return confirmed ?? false; +} + +class ProdukScreen extends StatefulWidget { + const ProdukScreen({super.key}); + + @override + State createState() => _ProdukScreenState(); +} + +class _ProdukScreenState extends State { + final TextEditingController _search = TextEditingController(); + + @override + void initState() { + super.initState(); + _search.addListener(() { + if (mounted) context.read().resetPagination(); + }); + } + + @override + void dispose() { + _search.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final state = context.watch(); + if (state.loading) { + return const Center(child: CircularProgressIndicator(color: kAccent)); + } + + final query = _search.text.toLowerCase(); + final filtered = state.products + .where((p) => + p.name.toLowerCase().contains(query) || + p.barcode.toLowerCase().contains(query)) + .toList(); + final products = filtered.take(state.visibleProductCount).toList(); + + return RefreshIndicator( + onRefresh: () async { + context.read().recordManualRefresh(); + await context.read().refresh(); + }, + color: kAccent, + child: Stack( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: Column( + children: [ + TextField( + controller: _search, + onChanged: (_) => setState(() {}), + style: const TextStyle(color: kText), + decoration: InputDecoration( + hintText: 'Cari produk...', + prefixIcon: const Icon(Icons.search, color: kMuted), + suffixIcon: _search.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.close, color: kMuted), + onPressed: () { + _search.clear(); + setState(() {}); + }, + ) + : null, + ), + ), + const SizedBox(height: 12), + Row( + children: [ + Text( + 'Daftar Produk', + style: const TextStyle( + fontSize: 15, fontWeight: FontWeight.w700), + ), + const Spacer(), + FilledButton.icon( + onPressed: () => _showAddForm(context, state), + icon: const Icon(Icons.add, size: 18), + label: const Text('Tambah Produk'), + style: FilledButton.styleFrom( + backgroundColor: kAccent, + foregroundColor: const Color(0xFF06210F), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + visualDensity: VisualDensity.compact, + ), + ), + ], + ), + const SizedBox(height: 12), + if (products.isEmpty) + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 40), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.inventory_2_outlined, size: 48, color: kMuted), + SizedBox(height: 8), + Text('Belum ada produk', style: TextStyle(color: kMuted)), + ], + ), + ), + ) + else + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: products.length, + separatorBuilder: (_, __) => const SizedBox(height: 10), + itemBuilder: (context, i) => + _ProductRow(p: products[i], state: state), + ), + if (state.hasMoreProducts) + Padding( + padding: const EdgeInsets.only(top: 12), + child: FilledButton.icon( + onPressed: () => state.loadMoreProducts(), + icon: const Icon(Icons.expand_more, size: 18), + label: Text('Muat lebih banyak (${state.products.length - state.visibleProductCount} tersisa)'), + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +void _showAddForm(BuildContext context, AppState state) { + final name = TextEditingController(); + final barcode = TextEditingController(); + final price = TextEditingController(); + final priceReseller = TextEditingController(); + final stock = TextEditingController(); + final minStockCtrl = TextEditingController(text: '5'); + final hargaPokokCtrl = TextEditingController(); + final focusNodes = [ + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + ]; + bool _listenersAdded = false; + final _sheetController = DraggableScrollableController(); + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) => DraggableScrollableSheet( + controller: _sheetController, + initialChildSize: 0.65, + minChildSize: 0.5, + maxChildSize: 0.92, + builder: (_, scrollController) { + if (!_listenersAdded) { + _listenersAdded = true; + for (final node in focusNodes) { + node.addListener(() { + if (node.hasFocus && context.mounted) { + _sheetController.animateTo( + 0.92, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + Future.delayed(const Duration(milliseconds: 350), () { + if (node.context != null && node.context!.mounted) { + Scrollable.ensureVisible( + node.context!, + duration: const Duration(milliseconds: 250), + alignment: 0.0, + ); + } + }); + } + }); + } + } + return Container( + decoration: const BoxDecoration( + color: kSurface, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + border: Border(top: BorderSide(color: kBorder)), + ), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only(top: 12), + width: 40, + height: 4, + decoration: BoxDecoration( + color: kBorder, + borderRadius: BorderRadius.circular(4), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + children: [ + const Icon(Icons.add_box_outlined, color: kAccent), + const SizedBox(width: 8), + const Text('Tambah Produk', + style: TextStyle( + fontSize: 16, fontWeight: FontWeight.w700)), + const Spacer(), + IconButton( + icon: const Icon(Icons.close, color: kMuted), + onPressed: () => Navigator.pop(sheetContext), + tooltip: 'Tutup', + ), + ], + ), + ), + const Divider(height: 12), + Expanded( + child: SingleChildScrollView( + controller: scrollController, + padding: EdgeInsets.fromLTRB(16, 8, 16, MediaQuery.of(context).viewInsets.bottom + 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: barcode, + focusNode: focusNodes[0], + decoration: InputDecoration( + labelText: 'Barcode / No. Produk', + prefixIcon: const Icon(Icons.qr_code_2_outlined), + suffixIcon: IconButton( + icon: const Icon(Icons.qr_code_scanner_outlined, color: kAccent), + onPressed: () async { + final code = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const ScanScreen( + title: 'Scan Barcode Produk', + ), + ), + ); + if (code != null && context.mounted) { + barcode.text = code; + } + }, + tooltip: 'Scan barcode', + )), + ), + const SizedBox(height: 10), + TextField( + controller: name, + focusNode: focusNodes[1], + decoration: const InputDecoration( + labelText: 'Nama produk', + prefixIcon: Icon(Icons.label_outline)), + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextField( + controller: price, + focusNode: focusNodes[2], + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration( + labelText: 'Harga Umum', + prefixText: 'Rp ', + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: priceReseller, + focusNode: focusNodes[3], + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration( + labelText: 'Harga Reseller', + prefixText: 'Rp ', + ), + ), + ), + ], + ), + const SizedBox(height: 10), + TextField( + controller: stock, + focusNode: focusNodes[4], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Stok awal', + prefixIcon: Icon(Icons.numbers), + ), + ), + const SizedBox(height: 10), + TextField( + controller: hargaPokokCtrl, + focusNode: focusNodes[5], + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration( + labelText: 'Harga Pokok (modal)', + prefixText: 'Rp ', + helperText: 'Kosongkan jika tidak diketahui', + ), + ), + const SizedBox(height: 10), + TextField( + controller: minStockCtrl, + focusNode: focusNodes[6], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Stok minimum (warning)', + prefixIcon: Icon(Icons.warning_outlined), + helperText: 'Default: 5', + ), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: () async { + final n = name.text.trim(); + final bc = barcode.text.trim(); + final pr = (RupiahInputFormatter.getRawValue(price.text) ?? 0) + .toDouble(); + final prR = + (RupiahInputFormatter.getRawValue(priceReseller.text) ?? pr) + .toDouble(); + final st = int.tryParse(stock.text) ?? 0; + final ms = int.tryParse(minStockCtrl.text) ?? 5; + final hp = (RupiahInputFormatter.getRawValue(hargaPokokCtrl.text) ?? 0) + .toDouble(); + if (n.isEmpty || pr <= 0) return; + if (!await confirmResellerWarning(context, pr, prR)) return; + final err = await state.addProduct(n, bc, pr, prR, st, ms, hp); + if (!context.mounted) return; + final messenger = ScaffoldMessenger.of(context); + if (err == null) { + name.clear(); + barcode.clear(); + price.clear(); + priceReseller.clear(); + stock.clear(); + minStockCtrl.clear(); + hargaPokokCtrl.clear(); + messenger.showSnackBar( + const SnackBar( + content: Text('Produk berhasil ditambahkan'), + backgroundColor: kSuccess, + ), + ); + Navigator.pop(sheetContext); + } else { + messenger.showSnackBar( + SnackBar( + content: Text('Gagal menambah produk: '), + backgroundColor: kDanger, + ), + ); + } + }, + icon: const Icon(Icons.add), + label: const Text('Tambah Produk'), + ), + ), + ], + ), + ), + ), + ], + ), + ); + }, + ), + ); +} + +void _showEditDialog(BuildContext context, AppState state, Product product) { + final name = TextEditingController(text: product.name); + final barcode = TextEditingController(text: product.barcode); + final price = TextEditingController( + text: RupiahInputFormatter.formatNumber(product.price.toInt())); + final priceReseller = TextEditingController( + text: RupiahInputFormatter.formatNumber(product.priceReseller.toInt())); + final stock = TextEditingController(text: product.stock.toString()); + final minStockCtrl = TextEditingController(text: product.minStock.toString()); + final hargaPokokCtrl = TextEditingController( + text: product.hargaPokok > 0 + ? RupiahInputFormatter.formatNumber(product.hargaPokok.toInt()) + : ''); + final focusNodes = [ + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + ]; + bool _listenersAdded = false; + final _sheetController = DraggableScrollableController(); + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) { + final bottomInset = MediaQuery.of(context).viewInsets.bottom; + return DraggableScrollableSheet( + controller: _sheetController, + initialChildSize: 0.65, + minChildSize: 0.5, + maxChildSize: 0.92, + builder: (_, scrollController) { + if (!_listenersAdded) { + _listenersAdded = true; + for (final node in focusNodes) { + node.addListener(() { + if (node.hasFocus && context.mounted) { + _sheetController.animateTo( + 0.92, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + Future.delayed(const Duration(milliseconds: 350), () { + if (node.context != null && node.context!.mounted) { + Scrollable.ensureVisible( + node.context!, + duration: const Duration(milliseconds: 250), + alignment: 0.0, + ); + } + }); + } + }); + } + } + return Container( + decoration: const BoxDecoration( + color: kSurface, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + border: Border(top: BorderSide(color: kBorder)), + ), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only(top: 12), + width: 40, + height: 4, + decoration: BoxDecoration( + color: kBorder, + borderRadius: BorderRadius.circular(4), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + children: [ + const Icon(Icons.edit_outlined, color: kAccent), + const SizedBox(width: 8), + const Text('Edit Produk', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)), + const Spacer(), + IconButton( + icon: const Icon(Icons.close, color: kMuted), + onPressed: () => Navigator.pop(sheetContext), + tooltip: 'Tutup', + ), + ], + ), + ), + const Divider(height: 12), + Expanded( + child: SingleChildScrollView( + controller: scrollController, + padding: EdgeInsets.fromLTRB(16, 8, 16, 16 + bottomInset), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: barcode, + focusNode: focusNodes[0], + decoration: const InputDecoration( + labelText: 'Barcode / No. Produk', + prefixIcon: Icon(Icons.qr_code_2_outlined)), + ), + const SizedBox(height: 10), + TextField( + controller: name, + focusNode: focusNodes[1], + decoration: const InputDecoration(labelText: 'Nama'), + ), + const SizedBox(height: 10), + TextField( + controller: price, + focusNode: focusNodes[2], + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration(labelText: 'Harga Umum', prefixText: 'Rp '), + ), + const SizedBox(height: 10), + TextField( + controller: priceReseller, + focusNode: focusNodes[3], + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration(labelText: 'Harga Reseller', prefixText: 'Rp '), + ), + const SizedBox(height: 10), + TextField( + controller: hargaPokokCtrl, + focusNode: focusNodes[4], + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration( + labelText: 'Harga Pokok (modal)', + prefixText: 'Rp ', + helperText: 'Kosongkan jika tidak diketahui', + ), + ), + const SizedBox(height: 10), + TextField( + controller: stock, + focusNode: focusNodes[5], + keyboardType: TextInputType.number, + decoration: const InputDecoration(labelText: 'Stok'), + ), + const SizedBox(height: 10), + TextField( + controller: minStockCtrl, + focusNode: focusNodes[6], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Stok minimum (warning)', + helperText: 'Default: 5', + ), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: () async { + final n = name.text.trim(); + final bc = barcode.text.trim(); + final pr = (RupiahInputFormatter.getRawValue(price.text) ?? 0) + .toDouble(); + final prR = + (RupiahInputFormatter.getRawValue(priceReseller.text) ?? pr) + .toDouble(); + final st = int.tryParse(stock.text) ?? 0; + final ms = int.tryParse(minStockCtrl.text) ?? 5; + final hp = (RupiahInputFormatter.getRawValue(hargaPokokCtrl.text) ?? 0) + .toDouble(); + if (n.isEmpty || pr <= 0) return; + if (!await confirmResellerWarning(context, pr, prR)) return; + final err = await state.updateProduct(product.id, n, bc, pr, prR, st, ms, hp); + if (!context.mounted) return; + final messenger = ScaffoldMessenger.of(context); + if (err == null) { + messenger.showSnackBar( + const SnackBar( + content: Text('Produk berhasil diperbarui'), + backgroundColor: kSuccess, + ), + ); + Navigator.pop(sheetContext); + } else { + messenger.showSnackBar( + SnackBar( + content: Text('Gagal memperbarui produk: '), + backgroundColor: kDanger, + ), + ); + } + }, + icon: const Icon(Icons.save), + label: const Text('Simpan'), + ), + ), + ], + ), + ), + ), + ], + ), + ); + }, + ); + }, + ); +} + +class _ProductRow extends StatelessWidget { + final Product p; + final AppState state; + const _ProductRow({required this.p, required this.state}); + + @override + Widget build(BuildContext context) { + final out = p.stock <= 0; + final lowStock = p.stock > 0 && p.stock <= p.minStock; + + return Card( + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + CircleAvatar( + radius: 22, + backgroundColor: kAccent.withValues(alpha: 0.15), + child: Text( + p.name.isNotEmpty ? p.name[0].toUpperCase() : '?', + style: + TextStyle(color: kAccent, fontWeight: FontWeight.w700), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(p.name, + style: const TextStyle( + fontSize: 15, fontWeight: FontWeight.w600)), + if (p.barcode.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + p.barcode, + style: const TextStyle( + fontSize: 11, color: kMuted, fontFamily: 'monospace'), + ), + ], + const SizedBox(height: 4), + Wrap( + spacing: 10, + runSpacing: 6, + children: [ + _Tag(formatRupiah(p.price), kSuccess), + if (p.priceReseller > 0) + _Tag('Rsl ${formatRupiah(p.priceReseller)}', kAccent), + if (p.hargaPokok > 0) + _Tag('Modal ${formatRupiah(p.hargaPokok)}', kAccent), + if (out) + _Tag('Stok habis', kDanger) + else if (lowStock) + _Tag('Stok rendah (${p.stock}/${p.minStock})', kAccent) + else + _Tag('Stok ${p.stock}', kMuted), + ], + ), + ], + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.edit_outlined, size: 20), + color: kAccent, + onPressed: () => _showEditDialog(context, state, p), + ), + IconButton( + icon: const Icon(Icons.delete_outline, size: 20), + color: kDanger, + onPressed: () async { + HapticFeedback.mediumImpact(); + final messenger = ScaffoldMessenger.of(context); + final confirm = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + icon: Icon(Icons.delete_outline, color: kDanger, size: 28), + title: const Text('Hapus Produk?'), + content: Text('Yakin ingin menghapus "${p.name}"?'), + actions: [ + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () => Navigator.pop(ctx, false), + style: OutlinedButton.styleFrom( + foregroundColor: kMuted, + side: const BorderSide(color: kBorder), + ), + child: const Text('Batal'), + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => Navigator.pop(ctx, true), + style: FilledButton.styleFrom( + backgroundColor: kDanger, + ), + child: const Text('Hapus'), + ), + ), + ], + ), + ); + if (confirm == true && context.mounted) { + final err = await state.deleteProduct(p.id); + if (err == null) { + messenger.showSnackBar( + const SnackBar( + content: Text('Produk berhasil dihapus'), + backgroundColor: kSuccess, + ), + ); + } else { + messenger.showSnackBar( + SnackBar( + content: Text('Gagal menghapus produk: $err'), + backgroundColor: kDanger, + ), + ); + } + } + }, + ), + ], + ), + ], + ), + ), + ); + } +} + +class _Tag extends StatelessWidget { + final String label; + final Color color; + const _Tag(this.label, this.color); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text(label, + style: TextStyle( + fontSize: 11, fontWeight: FontWeight.w600, color: color)), + ); + } +} diff --git a/lib/screens/riwayat_screen.dart b/lib/screens/riwayat_screen.dart new file mode 100644 index 0000000..98f2377 --- /dev/null +++ b/lib/screens/riwayat_screen.dart @@ -0,0 +1,1026 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/sale.dart'; +import '../services/export_service.dart'; +import '../services/printer_service.dart'; +import '../state/app_state.dart'; +import '../utils/colors.dart'; +import '../utils/format.dart'; +import '../utils/rupiah_input.dart'; + +class RiwayatScreen extends StatefulWidget { + const RiwayatScreen({super.key}); + + @override + State createState() => _RiwayatScreenState(); +} + +class _RiwayatScreenState extends State { + DateTimeRange? _dateRange; + String _paymentFilter = 'all'; + final PageController _reportPageController = PageController(viewportFraction: 0.85); + int _reportPage = 0; + + @override + Widget build(BuildContext context) { + final state = context.watch(); + if (state.loading) { + return const Center(child: CircularProgressIndicator(color: kAccent)); + } + + final now = DateTime.now(); + final isAdmin = state.isAdmin; + + List filteredSales; + if (isAdmin) { + if (_dateRange != null) { + final start = DateTime(_dateRange!.start.year, _dateRange!.start.month, + _dateRange!.start.day); + final end = DateTime(_dateRange!.end.year, _dateRange!.end.month, + _dateRange!.end.day + 1); + filteredSales = state.sales + .where((s) => s.date + .isAfter(start.subtract(const Duration(seconds: 1))) && + s.date.isBefore(end)) + .toList(); + } else { + filteredSales = state.sales + .where((s) => + s.date.year == now.year && + s.date.month == now.month) + .toList(); + } + } else { + filteredSales = state.sales + .where((s) => + s.date.year == now.year && + s.date.month == now.month && + s.date.day == now.day) + .toList(); + } + + if (_paymentFilter == 'unpaid') { + filteredSales = filteredSales.where((s) => s.paymentStatus != 'paid' && !s.isCancelled).toList(); + } else if (_paymentFilter == 'paid') { + filteredSales = filteredSales.where((s) => s.paymentStatus == 'paid' && !s.isCancelled).toList(); + } + + final displayedSales = filteredSales.take(state.visibleSalesCount).toList(); + + final currentMonth = DateTime(now.year, now.month); + final previousMonth = DateTime(now.year, now.month - 1); + + final currentMonthSales = state.sales.where((s) { + final saleMonth = DateTime(s.date.year, s.date.month); + return saleMonth == currentMonth && !s.isCancelled; + }).toList(); + + final previousMonthSales = state.sales.where((s) { + final saleMonth = DateTime(s.date.year, s.date.month); + return saleMonth == previousMonth && !s.isCancelled; + }).toList(); + + final currentRevenue = + currentMonthSales.fold(0.0, (sum, s) => sum + s.total); + final previousRevenue = + previousMonthSales.fold(0.0, (sum, s) => sum + s.total); + final revenueChange = previousRevenue > 0 + ? ((currentRevenue - previousRevenue) / previousRevenue) * 100 + : (currentRevenue > 0 ? 100 : 0); + + final currentProfit = + currentMonthSales.fold(0.0, (sum, s) => sum + (s.total - s.totalCost)); + final previousProfit = + previousMonthSales.fold(0.0, (sum, s) => sum + (s.total - s.totalCost)); + final profitChange = previousProfit > 0 + ? ((currentProfit - previousProfit) / previousProfit) * 100 + : (currentProfit > 0 ? 100 : 0); + + final currentTransactions = currentMonthSales.length; + final previousTransactions = previousMonthSales.length; + final transactionChange = previousTransactions > 0 + ? ((currentTransactions - previousTransactions) / previousTransactions) * 100 + : (currentTransactions > 0 ? 100 : 0); + + final today = DateTime(now.year, now.month, now.day); + final yesterday = DateTime(now.year, now.month, now.day - 1); + + final todaySales = state.sales.where((s) { + final saleDay = DateTime(s.date.year, s.date.month, s.date.day); + return saleDay == today && !s.isCancelled; + }).toList(); + + final yesterdaySales = state.sales.where((s) { + final saleDay = DateTime(s.date.year, s.date.month, s.date.day); + return saleDay == yesterday && !s.isCancelled; + }).toList(); + + final todayRevenue = todaySales.fold(0.0, (sum, s) => sum + s.total); + final yesterdayRevenue = yesterdaySales.fold(0.0, (sum, s) => sum + s.total); + final revenueDayChange = yesterdayRevenue > 0 + ? ((todayRevenue - yesterdayRevenue) / yesterdayRevenue) * 100 + : (todayRevenue > 0 ? 100 : 0); + + final reports = <_Report>[ + if (isAdmin) ...[ + _Report( + 'Pendapatan Bulan Ini', + formatRupiah(currentRevenue), + Icons.trending_up, + kSuccess, + change: revenueChange.toDouble(), + compareValue: formatRupiah(previousRevenue), + compareLabel: 'Bulan Lalu', + ), + _Report( + 'Laba Kotor Bulan Ini', + formatRupiah(currentProfit), + Icons.attach_money, + kAccent, + change: profitChange.toDouble(), + compareValue: formatRupiah(previousProfit), + compareLabel: 'Bulan Lalu', + ), + _Report( + 'Transaksi Bulan Ini', + '$currentTransactions', + Icons.receipt_long, + kAccent, + change: transactionChange.toDouble(), + compareValue: '$previousTransactions', + compareLabel: 'Bulan Lalu', + ), + ] else ...[ + _Report( + 'Transaksi Hari Ini', + '$currentTransactions', + Icons.receipt_long, + kAccent, + change: transactionChange.toDouble(), + compareValue: '$previousTransactions', + compareLabel: 'Kemarin', + ), + _Report( + 'Pendapatan Hari Ini', + formatRupiah(todayRevenue), + Icons.today_outlined, + kSuccess, + change: revenueDayChange.toDouble(), + compareValue: formatRupiah(yesterdayRevenue), + compareLabel: 'Kemarin', + ), + ], + ]; + + return Padding( + padding: const EdgeInsets.all(12), + child: Column( + children: [ + if (isAdmin) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + _dateRange == null + ? 'Semua data' + : '${formatTanggal(_dateRange!.start)} - ${formatTanggal(_dateRange!.end)}', + style: const TextStyle(color: kMuted, fontSize: 13), + ), + ), + ], + ), + const SizedBox(height: 8), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + TextButton.icon( + onPressed: () async { + final messenger = ScaffoldMessenger.of(context); + try { + final picked = await showDateRangePicker( + context: context, + firstDate: DateTime(2024), + lastDate: DateTime.now(), + initialDateRange: _dateRange, + ); + if (mounted && picked != null) { + setState(() => _dateRange = picked); + context.read().resetPagination(); + } + } catch (e) { + if (mounted) { + messenger.showSnackBar( + SnackBar( + content: Text('Gagal memilih tanggal: $e'), + backgroundColor: kDanger, + ), + ); + } + } + }, + icon: const Icon(Icons.date_range_outlined, size: 18), + label: const Text('Pilih Rentang Tanggal'), + ), + if (_dateRange != null) + TextButton.icon( + onPressed: () { + try { + setState(() => _dateRange = null); + context.read().resetPagination(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Gagal reset filter: $e'), + backgroundColor: kDanger, + ), + ); + } + } + }, + icon: const Icon(Icons.close, size: 18), + label: const Text('Reset'), + ), + IconButton( + icon: const Icon(Icons.picture_as_pdf_outlined, + size: 18), + onPressed: () async { + final messenger = ScaffoldMessenger.of(context); + try { + if (filteredSales.isEmpty) { + if (mounted) { + messenger.showSnackBar( + const SnackBar( + content: + Text('Tidak ada data untuk export'), + backgroundColor: kDanger, + ), + ); + } + return; + } + final exportService = ExportService(); + final path = await exportService.exportToPdf( + filteredSales + .map((s) => { + 'date': s.date, + 'id': s.id.toUpperCase(), + 'total': formatRupiah(s.total), + 'paid': formatRupiah(s.paid), + 'change': formatRupiah(s.change), + 'items': s.items.length, + 'discount': s.discount, + }) + .toList(), + 'Dutra Store', + _dateRange, + ); + if (path != null && mounted) { + await exportService.shareFile(path); + } + } catch (e) { + if (mounted) { + messenger.showSnackBar( + SnackBar( + content: Text('Gagal export PDF: $e'), + backgroundColor: kDanger, + ), + ); + } + } + }, + tooltip: 'Export PDF', + ), + ], + ), + ), + ], + ), + ), + Column( + children: [ + SizedBox( + height: 90, + child: PageView.builder( + controller: _reportPageController, + onPageChanged: (i) => setState(() => _reportPage = i), + itemCount: reports.length, + itemBuilder: (context, i) { + final r = reports[i]; + return Padding( + padding: EdgeInsets.only( + right: i < reports.length - 1 ? 8 : 0, + ), + child: _ReportCard( + report: r, + isActive: i == _reportPage, + ), + ); + }, + ), + ), + const SizedBox(height: 2), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(reports.length, (i) { + return AnimatedContainer( + duration: const Duration(milliseconds: 220), + width: _reportPage == i ? 12 : 5, + height: 5, + margin: const EdgeInsets.symmetric(horizontal: 2), + decoration: BoxDecoration( + color: _reportPage == i + ? reports[i].color + : kBorder, + borderRadius: BorderRadius.circular(999), + ), + ); + }), + ), + ], + ), + const SizedBox(height: 6), + if (isAdmin) _buildUnpaidSummary(state.sales, () => setState(() => _paymentFilter = 'unpaid')), + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + _PaymentFilterChip( + label: 'Semua', + selected: _paymentFilter == 'all', + onTap: () => setState(() => _paymentFilter = 'all'), + ), + _PaymentFilterChip( + label: 'Belum Lunas', + selected: _paymentFilter == 'unpaid', + onTap: () => setState(() => _paymentFilter = 'unpaid'), + isWarning: true, + ), + _PaymentFilterChip( + label: 'Sudah Lunas', + selected: _paymentFilter == 'paid', + onTap: () => setState(() => _paymentFilter = 'paid'), + isSuccess: true, + ), + ], + ), + const SizedBox(height: 8), + Expanded( + child: filteredSales.isEmpty + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon(Icons.receipt_long_outlined, + size: 48, color: kMuted), + SizedBox(height: 8), + Text('Belum ada transaksi', + style: TextStyle(color: kMuted)), + ], + ), + ) + : RefreshIndicator( + onRefresh: () async { + context.read().recordManualRefresh(); + await context.read().refresh(); + }, + color: kAccent, + child: ListView.separated( + itemCount: displayedSales.length + (state.hasMoreSales ? 1 : 0), + separatorBuilder: (_, __) => + const SizedBox(height: 10), + itemBuilder: (context, i) { + if (i >= displayedSales.length) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: FilledButton.icon( + onPressed: () => state.loadMoreSales(), + icon: const Icon(Icons.expand_more, size: 18), + label: Text('Muat lebih banyak (${filteredSales.length - state.visibleSalesCount} tersisa)'), + ), + ); + } + final sale = displayedSales[i]; + final isCancelled = sale.isCancelled; + return Card( + color: isCancelled ? kDanger.withValues(alpha: 0.08) : null, + child: InkWell( + onTap: () => _showSaleDetail(context, sale), + borderRadius: BorderRadius.circular(kRadius), + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + CircleAvatar( + radius: 18, + backgroundColor: isCancelled + ? kDanger.withValues(alpha: 0.12) + : kSuccess.withValues(alpha: 0.12), + child: Icon( + isCancelled + ? Icons.cancel_outlined + : Icons.check_circle_outline, + color: isCancelled ? kDanger : kSuccess, + size: 20, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + formatRupiah(sale.total), + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + decoration: isCancelled + ? TextDecoration.lineThrough + : null, + color: isCancelled ? kMuted : null, + ), + ), + const SizedBox(height: 2), + Text( + '${formatTanggal(sale.date)} ${formatWaktu(sale.date)} • ${sale.items.length} item', + style: const TextStyle(fontSize: 11, color: kMuted), + ), + if (isCancelled) ...[ + const SizedBox(height: 2), + Text( + 'Dibatalkan', + style: const TextStyle( + fontSize: 10, + color: kDanger, + fontWeight: FontWeight.w600, + ), + ), + ], + ], + ), + ), + const SizedBox(width: 6), + Text( + '#${sale.id.toUpperCase()}', + style: const TextStyle(fontSize: 10, color: kMuted), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ), + ); + }, + ), + ), + ), + ], + ), + ); + } + + void _showSaleDetail(BuildContext context, Sale sale) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) => DraggableScrollableSheet( + initialChildSize: 0.7, + minChildSize: 0.5, + maxChildSize: 0.92, + builder: (_, controller) => _buildSaleDetailBottomSheet( + context, + sheetContext, + sale, + controller, + ), + ), + ); + } + + Widget _buildSaleDetailBottomSheet( + BuildContext parentContext, BuildContext sheetContext, Sale sale, ScrollController controller) { + final state = parentContext.read(); + final isAdmin = state.isAdmin; + final isCancelled = sale.isCancelled; + + return Container( + decoration: const BoxDecoration( + color: kSurface, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + border: Border(top: BorderSide(color: kBorder)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only(top: 12), + width: 40, + height: 4, + decoration: BoxDecoration( + color: kBorder, + borderRadius: BorderRadius.circular(4), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('#${sale.id.toUpperCase()}', + style: const TextStyle(fontSize: 10, color: kMuted), + overflow: TextOverflow.ellipsis), + Text( + 'Kasir: ${state.getProfileName(sale.userId)}', + style: const TextStyle(color: kMuted, fontSize: 11), + ), + ], + ), + ), + if (isCancelled) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: kDanger.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(8), + ), + child: const Text( + 'DIBATALKAN', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w700, + color: kDanger), + ), + ), + ], + ), + ), + const SizedBox(height: 2), + Text( + '${formatTanggal(sale.date)} ${formatWaktu(sale.date)}', + style: const TextStyle(color: kMuted, fontSize: 12), + ), + const Divider(height: 24), + Expanded( + child: SingleChildScrollView( + controller: controller, + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ...sale.items.map((it) => Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text('${it.name} x${it.qty}', + style: const TextStyle(fontSize: 14)), + ), + Text(formatRupiah(it.subtotal), + style: const TextStyle( + fontSize: 14, fontWeight: FontWeight.w600)), + ], + ), + )), + if (sale.discount > 0) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Diskon', style: TextStyle(color: kMuted)), + Text('-${formatRupiah(sale.discount)}', + style: const TextStyle(color: kMuted)), + ], + ), + ), + const Divider(height: 24), + _receiptRow('Total', formatRupiah(sale.total), true), + _receiptRow('Bayar', formatRupiah(sale.paid), false), + if (sale.paymentStatus == 'unpaid' || sale.paymentStatus == 'partial') + _receiptRow('Sisa', formatRupiah(sale.dueAmount), false), + _receiptRow('Kembali', formatRupiah(sale.change), false), + _receiptRow('Metode', _paymentMethodLabel(sale.paymentMethod), false), + _receiptRow('Status', sale.paymentStatus == 'paid' ? 'Lunas' : 'Belum Lunas', false), + if (sale.splitPayment != null && sale.splitPayment!.isNotEmpty) + ...sale.splitPayment!.entries.map((e) { + final label = e.key == 'tunai' + ? 'Tunai' + : e.key == 'transfer' + ? 'Bank' + : 'QRIS'; + return _receiptRow('Split $label', formatRupiah(e.value), false); + }), + if (sale.totalCost > 0) ...[ + const Divider(height: 24), + _receiptRow('Harga Pokok', formatRupiah(sale.totalCost), false), + _receiptRow('Laba Kotor', formatRupiah(sale.total - sale.totalCost), true), + ], + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: isCancelled + ? null + : () async { + final messenger = ScaffoldMessenger.of(context); + final prefs = await SharedPreferences.getInstance(); + final storeName = + prefs.getString('store_name') ?? 'Toko Grosir'; + final err = + await printerService.printSale( + sale, + storeName, + kasirName: state.getProfileName(sale.userId), + whatsapp: prefs.getString('store_whatsapp'), + notes: prefs.getString('store_notes'), + ); + if (mounted) { + messenger.showSnackBar( + SnackBar( + content: Text(err == null + ? 'Struk dikirim ke printer' + : 'Gagal cetak: $err'), + backgroundColor: err == null ? kSuccess : kDanger, + ), + ); + } + }, + icon: const Icon(Icons.print_outlined), + label: const Text('Cetak Struk'), + ), + ), + if (isAdmin && !isCancelled && sale.paymentStatus != 'paid') ...[ + const SizedBox(height: 4), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: () async { + final payCtrl = TextEditingController(); + final result = await showDialog( + context: parentContext, + builder: (ctx) => AlertDialog( + title: Text(sale.paymentStatus == 'unpaid' ? 'Terima Pembayaran' : 'Bayar Sisa'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Total: ${formatRupiah(sale.total)}'), + Text('Sudah bayar: ${formatRupiah(sale.paid)}'), + Text('Sisa: ${formatRupiah(sale.dueAmount)}'), + const SizedBox(height: 12), + TextField( + controller: payCtrl, + keyboardType: TextInputType.number, + inputFormatters: [RupiahInputFormatter()], + decoration: const InputDecoration( + labelText: 'Nominal Pembayaran', + prefixText: 'Rp ', + ), + ), + ], + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Batal')), + FilledButton( + onPressed: () { + final val = (RupiahInputFormatter.getRawValue(payCtrl.text) ?? 0).toDouble(); + if (val <= 0) return; + Navigator.pop(ctx, val); + }, + style: FilledButton.styleFrom(backgroundColor: kSuccess), + child: const Text('Simpan'), + ), + ], + ), + ); + if (result != null && result > 0) { + final err = await state.recordPayment(sale.id, result); + if (mounted) { + final messenger = ScaffoldMessenger.of(parentContext); + messenger.showSnackBar( + SnackBar( + content: Text(err == null ? 'Pembayaran berhasil dicatat' : 'Gagal: $err'), + backgroundColor: err == null ? kSuccess : kDanger, + ), + ); + } + } + }, + icon: const Icon(Icons.payments_outlined, color: Colors.white), + label: Text(sale.paymentStatus == 'unpaid' ? 'Terima Pembayaran' : 'Bayar Sisa'), + style: FilledButton.styleFrom( + backgroundColor: kSuccess, + foregroundColor: const Color(0xFF06210F), + ), + ), + ), + ], + if (isAdmin && !isCancelled) ...[ + const SizedBox(height: 4), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: () async { + final messenger = ScaffoldMessenger.of(parentContext); + final confirm = await showDialog( + context: parentContext, + builder: (ctx) => AlertDialog( + icon: Icon(Icons.cancel_outlined, color: kDanger, size: 28), + title: const Text('Batalkan Transaksi?'), + content: const Text( + 'Stok akan dikembalikan secara otomatis. Tindakan ini tidak dapat dibatalkan.', + ), + actions: [ + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () => Navigator.pop(ctx, false), + style: OutlinedButton.styleFrom( + foregroundColor: kMuted, + side: const BorderSide(color: kBorder), + ), + child: const Text('Batal'), + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => Navigator.pop(ctx, true), + style: FilledButton.styleFrom( + backgroundColor: kDanger, + ), + child: const Text('Batalkan'), + ), + ), + ], + ), + ); + if (confirm == true && mounted) { + final err = await state.cancelSale(sale.id); + if (mounted) { + Navigator.pop(sheetContext); + messenger.showSnackBar( + SnackBar( + content: Text(err == null + ? 'Transaksi dibatalkan, stok dipulihkan' + : 'Gagal membatalkan: $err'), + backgroundColor: err == null ? kSuccess : kDanger, + ), + ); + } + } + }, + icon: const Icon(Icons.cancel_outlined, color: kDanger), + label: const Text('Batalkan Transaksi'), + style: OutlinedButton.styleFrom( + foregroundColor: kDanger, + side: const BorderSide(color: kDanger), + ), + ), + ), + ], + ], + ), + ), + ), + ], + ), + ); + } + + Widget _receiptRow(String label, String value, bool bold) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label, + style: TextStyle( + color: bold ? kText : kMuted, + fontWeight: bold ? FontWeight.w700 : FontWeight.normal)), + Text(value, + style: TextStyle( + fontSize: bold ? 17 : 14, + fontWeight: bold ? FontWeight.w800 : FontWeight.w600, + color: bold ? kAccent : kText, + )), + ], + ), + ); + } +} + +class _ReportCard extends StatelessWidget { + final _Report report; + final bool isActive; + const _ReportCard({required this.report, required this.isActive}); + + @override + Widget build(BuildContext context) { + final r = report; + return AnimatedContainer( + duration: const Duration(milliseconds: 220), + curve: Curves.easeInOut, + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: kSurface2, + borderRadius: BorderRadius.circular(kRadius), + border: Border.all( + color: isActive ? r.color.withValues(alpha: 0.4) : kBorder, + ), + ), + child: isActive + ? Row( + children: [ + Container( + padding: const EdgeInsets.all(3), + decoration: BoxDecoration( + color: r.color.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(6), + ), + child: Icon(r.icon, color: r.color, size: 14), + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + r.value, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w800, + color: r.color, + ), + ), + Text( + r.label, + style: const TextStyle(fontSize: 10, color: kMuted), + ), + if (r.change != null) ...[ + const SizedBox(height: 1), + Text( + '${r.change! >= 0 ? '↑' : '↓'} ${r.change!.abs().toStringAsFixed(1)}% vs ${r.compareLabel}${r.compareValue != null ? " • ${r.compareValue}" : ""}', + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.w600, + color: r.change! >= 0 ? kSuccess : kDanger, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ], + ), + ), + ], + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: r.color.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(6), + ), + child: Icon(r.icon, color: r.color, size: 11), + ), + const SizedBox(height: 2), + Text( + r.value, + style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w800), + ), + Text( + r.label, + style: const TextStyle(fontSize: 8, color: kMuted), + ), + ], + ), + ); + } +} + +Widget _buildUnpaidSummary(List sales, VoidCallback onTap) { + final unpaid = sales.where((s) => s.paymentStatus != 'paid' && !s.isCancelled).toList(); + if (unpaid.isEmpty) return const SizedBox.shrink(); + final totalDue = unpaid.fold(0.0, (sum, s) => sum + s.dueAmount); + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: kAccent.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(kRadius), + border: Border.all(color: kAccent.withValues(alpha: 0.2)), + ), + child: Row( + children: [ + Icon(Icons.warning_amber_rounded, color: kAccent, size: 20), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text('${unpaid.length} Transaksi Belum Lunas', + style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)), + Text('Total sisa: ${formatRupiah(totalDue)}', + style: TextStyle(fontSize: 11, color: kMuted)), + ], + ), + ), + TextButton.icon( + onPressed: onTap, + icon: const Icon(Icons.visibility_outlined, size: 16), + label: const Text('Lihat'), + ), + ], + ), + ); +} + +class _PaymentFilterChip extends StatelessWidget { + final String label; + final bool selected; + final VoidCallback onTap; + final bool isWarning; + final bool isSuccess; + + const _PaymentFilterChip({ + required this.label, + required this.selected, + required this.onTap, + this.isWarning = false, + this.isSuccess = false, + }); + + @override + Widget build(BuildContext context) { + final color = isWarning + ? kAccent + : isSuccess + ? kSuccess + : kMuted; + return FilterChip( + label: Text(label, style: const TextStyle(fontSize: 12)), + selected: selected, + onSelected: (_) => onTap(), + selectedColor: color.withValues(alpha: 0.15), + checkmarkColor: color, + labelStyle: TextStyle(color: selected ? color : kMuted, fontSize: 12), + side: BorderSide(color: selected ? color : kBorder), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + ); + } +} + +String _paymentMethodLabel(String method) { + switch (method) { + case 'transfer': + return 'Bank'; + case 'qris': + return 'QRIS'; + case 'split': + return 'Split Payment'; + default: + return 'Tunai'; + } +} + +class _Report { + final String label; + final String value; + final IconData icon; + final Color color; + final double? change; + final String? compareValue; + final String? compareLabel; + + const _Report( + this.label, + this.value, + this.icon, + this.color, { + this.change, + this.compareValue, + this.compareLabel, + }); +} diff --git a/lib/screens/scan_screen.dart b/lib/screens/scan_screen.dart new file mode 100644 index 0000000..a91f828 --- /dev/null +++ b/lib/screens/scan_screen.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; + +class ScanScreen extends StatefulWidget { + final String title; + + const ScanScreen({ + super.key, + required this.title, + }); + + @override + State createState() => _ScanScreenState(); +} + +class _ScanScreenState extends State { + final MobileScannerController _controller = MobileScannerController(); + bool _isScanned = false; + + void _handleBarcode(BarcodeCapture capture) { + if (_isScanned) return; + + final barcode = capture.barcodes.firstOrNull; + if (barcode != null && barcode.rawValue != null) { + final code = barcode.rawValue!.trim(); + if (code.isNotEmpty) { + _isScanned = true; + _controller.stop(); + Navigator.pop(context, code); + } + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(widget.title), + centerTitle: true, + ), + body: MobileScanner( + controller: _controller, + onDetect: _handleBarcode, + ), + ); + } +} + diff --git a/lib/services/export_service.dart b/lib/services/export_service.dart new file mode 100644 index 0000000..f09ebfe --- /dev/null +++ b/lib/services/export_service.dart @@ -0,0 +1,167 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:path_provider/path_provider.dart'; +import 'package:share_plus/share_plus.dart'; + +class ExportService { + static final ExportService _instance = ExportService._internal(); + factory ExportService() => _instance; + ExportService._internal(); + + Future exportToPdf(List> transactions, + String storeName, DateTimeRange? dateRange) async { + try { + debugPrint('exportToPdf called with ${transactions.length} transactions'); + final pdf = pw.Document(); + + pdf.addPage( + pw.Page( + build: (context) { + return pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + pw.Text(storeName, style: pw.TextStyle(fontSize: 24, fontWeight: pw.FontWeight.bold)), + pw.SizedBox(height: 8), + if (dateRange != null) + pw.Text('${_formatDate(dateRange.start)} - ${_formatDate(dateRange.end)}', + style: pw.TextStyle(fontSize: 12)), + pw.SizedBox(height: 16), + pw.Table( + border: pw.TableBorder.all(), + children: [ + pw.TableRow( + children: [ + pw.Padding(padding: pw.EdgeInsets.all(8), child: pw.Text('Tanggal', style: pw.TextStyle(fontWeight: pw.FontWeight.bold))), + pw.Padding(padding: pw.EdgeInsets.all(8), child: pw.Text('ID', style: pw.TextStyle(fontWeight: pw.FontWeight.bold))), + pw.Padding(padding: pw.EdgeInsets.all(8), child: pw.Text('Total', style: pw.TextStyle(fontWeight: pw.FontWeight.bold))), + pw.Padding(padding: pw.EdgeInsets.all(8), child: pw.Text('Bayar', style: pw.TextStyle(fontWeight: pw.FontWeight.bold))), + pw.Padding(padding: pw.EdgeInsets.all(8), child: pw.Text('Kembali', style: pw.TextStyle(fontWeight: pw.FontWeight.bold))), + ], + ), + for (final tx in transactions) + pw.TableRow( + children: [ + pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text(_formatDate(tx['date']))), + pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text(tx['id'])), + pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text(tx['total'])), + pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text(tx['paid'])), + pw.Padding(padding: const pw.EdgeInsets.all(8), child: pw.Text(tx['change'])), + ], + ), + ], + ), + ], + ); + }, + ), + ); + + Directory? directory; + try { + directory = await getTemporaryDirectory(); + debugPrint('PDF using temporary directory: ${directory.path}'); + } catch (e) { + debugPrint('getTemporaryDirectory failed for PDF: $e'); + return null; + } + + final file = File('${directory.path}/laporan_transaksi_${DateTime.now().millisecondsSinceEpoch}.pdf'); + try { + await file.writeAsBytes(await pdf.save()); + debugPrint('PDF file written: ${file.path}, exists: ${await file.exists()}'); + } catch (e) { + debugPrint('Failed to write PDF file: $e'); + return null; + } + + return file.path; + } catch (e) { + debugPrint('exportToPdf error: $e'); + return null; + } + } + + Future exportToCsv(List> transactions) async { + try { + debugPrint('=== CSV Export Started ==='); + debugPrint('Transactions count: ${transactions.length}'); + + if (transactions.isEmpty) { + debugPrint('No transactions to export'); + return null; + } + + final buffer = StringBuffer(); + buffer.writeln('Tanggal,ID Transaksi,Total,Bayar,Kembali,Item,Diskon'); + + for (final tx in transactions) { + final date = _formatDate(tx['date']); + final id = tx['id']; + final total = tx['total']; + final paid = tx['paid']; + final change = tx['change']; + final items = tx['items'] is List ? (tx['items'] as List).length : (tx['items'] as int? ?? 0); + final discount = tx['discount'] ?? 0; + + buffer.writeln('$date,$id,$total,$paid,$change,$items,$discount'); + } + + debugPrint('CSV buffer created, length: ${buffer.toString().length}'); + + String? filePath; + try { + final tempDir = await getTemporaryDirectory(); + debugPrint('Temp dir: ${tempDir.path}'); + + final timestamp = DateTime.now().millisecondsSinceEpoch; + final fileName = 'laporan_transaksi_$timestamp.csv'; + filePath = '${tempDir.path}/$fileName'; + + final file = File(filePath); + await file.writeAsString(buffer.toString()); + debugPrint('CSV file written: $filePath'); + debugPrint('File exists: ${await file.exists()}'); + debugPrint('File size: ${await file.length()}'); + } catch (e) { + debugPrint('Error creating CSV file: $e'); + return null; + } + + debugPrint('=== CSV Export Completed Successfully ==='); + return filePath; + } catch (e) { + debugPrint('=== CSV Export Failed ==='); + debugPrint('Error: $e'); + debugPrint('Stack trace: ${StackTrace.current}'); + return null; + } + } + + Future shareFile(String filePath) async { + try { + debugPrint('Sharing file: $filePath'); + final file = File(filePath); + final exists = await file.exists(); + debugPrint('File exists: $exists, size: ${exists ? await file.length() : 0}'); + + if (!exists) { + debugPrint('File does not exist, cannot share'); + return; + } + + await Share.shareXFiles([XFile(filePath)], text: 'Laporan Transaksi'); + debugPrint('Share completed'); + } catch (e) { + debugPrint('shareFile error: $e'); + rethrow; + } + } + + String _formatDate(dynamic date) { + if (date is DateTime) { + return '${date.day}/${date.month}/${date.year}'; + } + return date.toString(); + } +} \ No newline at end of file diff --git a/lib/services/offline_queue_service.dart b/lib/services/offline_queue_service.dart new file mode 100644 index 0000000..51e3323 --- /dev/null +++ b/lib/services/offline_queue_service.dart @@ -0,0 +1,156 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class OfflineQueueService { + static final OfflineQueueService _instance = OfflineQueueService._internal(); + factory OfflineQueueService() => _instance; + OfflineQueueService._internal(); + + final SupabaseClient _supabase = Supabase.instance.client; + final Connectivity _connectivity = Connectivity(); + List> _queue = []; + bool _isOnline = true; + bool _syncing = false; + + static const Duration _timeout = Duration(seconds: 30); + + Future _withTimeout(Future future, [String? operation]) async { + try { + return await future.timeout( + _timeout, + onTimeout: () => throw TimeoutException('${operation ?? 'Operasi'} timeout setelah $_timeout'), + ); + } on TimeoutException catch (e) { + print('OfflineQueue timeout: $e'); + rethrow; + } + } + + List> get queue => List.unmodifiable(_queue); + bool get isOnline => _isOnline; + bool get hasPendingItems => _queue.isNotEmpty; + + Future init() async { + await _loadQueue(); + _connectivity.onConnectivityChanged.listen(_updateConnectionStatus); + await _checkConnection(); + if (_isOnline) await _processQueue(); + } + + Future _loadQueue() async { + final prefs = await SharedPreferences.getInstance(); + final queueJson = prefs.getString('offline_queue'); + if (queueJson != null) { + final List decoded = json.decode(queueJson); + _queue = decoded.cast>(); + } + } + + Future _saveQueue() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('offline_queue', json.encode(_queue)); + } + + Future _checkConnection() async { + final result = await _connectivity.checkConnectivity(); + _updateConnectionStatus(result); + } + + void _updateConnectionStatus(List result) { + _isOnline = result.any((r) => r != ConnectivityResult.none); + if (_isOnline && _queue.isNotEmpty) { + _processQueue(); + } + } + + Future addToQueue(Map transaction) async { + _queue.add(transaction); + await _saveQueue(); + if (_isOnline) { + await _processQueue(); + } + } + + Future _processQueue() async { + if (_syncing || !_isOnline || _queue.isEmpty) return; + _syncing = true; + + while (_queue.isNotEmpty && _isOnline) { + final item = _queue.first; + try { + await _processTransaction(item); + _queue.removeAt(0); + await _saveQueue(); + } catch (e) { + _syncing = false; + return; + } + } + _syncing = false; + } + + Future _processTransaction(Map transaction) async { + final sale = transaction['sale'] as Map; + final items = (transaction['items'] as List?) ?? []; + + final saleId = sale['id'] as String; + final existing = await _withTimeout( + _supabase + .from('sales') + .select('id, total_cost') + .eq('id', saleId) + .maybeSingle(), + 'Check existing sale', + ); + + if (existing == null) { + await _withTimeout( + _supabase.from('sales').insert(sale), + 'Insert queued sale', + ); + } else { + final existingTotalCost = (existing['total_cost'] as num?)?.toDouble() ?? 0; + if (existingTotalCost <= 0 && sale['total_cost'] != null) { + await _withTimeout( + _supabase + .from('sales') + .update({'total_cost': sale['total_cost']}) + .eq('id', saleId), + 'Update sale total_cost', + ); + } + } + + for (final it in items) { + final productId = it['product_id'] as String; + final qty = (it['qty'] as num).toInt(); + final product = await _withTimeout( + _supabase + .from('products') + .select() + .eq('id', productId) + .maybeSingle(), + 'Load product for stock update', + ); + if (product != null) { + final currentStock = (product['stock'] as num).toInt(); + final newStock = (currentStock - qty).clamp(0, 1 << 62); + await _withTimeout( + _supabase + .from('products') + .update({'stock': newStock}) + .eq('id', productId), + 'Update product stock', + ); + } + } + } + + Future clearQueue() async { + _queue.clear(); + await _saveQueue(); + } +} \ No newline at end of file diff --git a/lib/services/printer_service.dart b/lib/services/printer_service.dart new file mode 100644 index 0000000..93719a4 --- /dev/null +++ b/lib/services/printer_service.dart @@ -0,0 +1,223 @@ +import 'package:esc_pos_utils_plus/esc_pos_utils_plus.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../models/sale.dart'; +import '../utils/format.dart'; + +class PrinterService { + static const String _printerKey = 'selected_printer_mac'; + + String? _connectedMac; + bool _isConnected = false; + + String? get connectedMac => _connectedMac; + bool get isConnected => _isConnected; + + Future init() async { + final prefs = await SharedPreferences.getInstance(); + _connectedMac = prefs.getString(_printerKey); + if (_connectedMac != null) { + await connect(_connectedMac!); + } + } + + Future isBluetoothEnabled() async { + return PrintBluetoothThermal.bluetoothEnabled; + } + + Future> getPairedDevices() async { + final list = await PrintBluetoothThermal.pairedBluetooths; + return list; + } + + Future connect(String mac) async { + try { + final connected = await PrintBluetoothThermal.connect(macPrinterAddress: mac); + _isConnected = connected; + if (connected) { + _connectedMac = mac; + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_printerKey, mac); + } + return connected; + } catch (_) { + _isConnected = false; + return false; + } + } + + Future disconnect() async { + try { + await PrintBluetoothThermal.disconnect; + } catch (_) {} + _isConnected = false; + } + + Future forgetPrinter() async { + _connectedMac = null; + _isConnected = false; + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_printerKey); + } + + Future> _buildReceiptBytes(Sale sale, String storeName, {String? kasirName, String? whatsapp, String? notes}) async { + final profile = await CapabilityProfile.load(); + final generator = Generator(PaperSize.mm58, profile); + final bytes = []; + + bytes.addAll(generator.text( + storeName, + styles: const PosStyles( + align: PosAlign.center, + bold: true, + height: PosTextSize.size2, + ), + )); + bytes.addAll(generator.text( + formatTanggal(sale.date), + styles: const PosStyles(align: PosAlign.center), + )); + bytes.addAll(generator.text( + formatWaktu(sale.date), + styles: const PosStyles(align: PosAlign.center), + )); + bytes.addAll(generator.text( + '#${sale.id.toUpperCase()}', + styles: const PosStyles(align: PosAlign.center), + )); + bytes.addAll(generator.hr()); + + for (final it in sale.items) { + bytes.addAll(generator.text('${it.name} x${it.qty}', + styles: const PosStyles(bold: true))); + bytes.addAll(generator.row([ + PosColumn( + text: formatRupiah(it.price), + width: 6, + ), + PosColumn( + text: formatRupiah(it.subtotal), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ])); + } + + bytes.addAll(generator.hr()); + if (sale.discount > 0) { + bytes.addAll(generator.row([ + PosColumn(text: 'Diskon', width: 6), + PosColumn( + text: '-${formatRupiah(sale.discount)}', + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ])); + } + bytes.addAll(generator.row([ + PosColumn( + text: 'TOTAL', + width: 6, + styles: const PosStyles(bold: true), + ), + PosColumn( + text: formatRupiah(sale.total), + width: 6, + styles: const PosStyles(bold: true, align: PosAlign.right), + ), + ])); + final methodLabel = sale.paymentMethod == 'transfer' + ? 'Bank' + : sale.paymentMethod == 'qris' + ? 'QRIS' + : sale.paymentMethod == 'split' + ? 'Split Payment' + : 'Tunai'; + bytes.addAll(generator.row([ + PosColumn(text: 'Metode', width: 6), + PosColumn( + text: methodLabel, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ])); + if (sale.paymentMethod == 'tunai') { + bytes.addAll(generator.row([ + PosColumn(text: 'Bayar', width: 6), + PosColumn( + text: formatRupiah(sale.paid), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ])); + bytes.addAll(generator.row([ + PosColumn(text: 'Kembali', width: 6), + PosColumn( + text: formatRupiah(sale.change), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ])); + } + if (sale.splitPayment != null && sale.splitPayment!.isNotEmpty) { + for (final entry in sale.splitPayment!.entries) { + final label = entry.key == 'tunai' + ? 'Tunai' + : entry.key == 'transfer' + ? 'Transfer' + : 'QRIS'; + bytes.addAll(generator.row([ + PosColumn(text: 'Split $label', width: 6), + PosColumn( + text: formatRupiah(entry.value), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ])); + } + } + bytes.addAll(generator.hr()); + if (kasirName != null && kasirName.isNotEmpty) { + bytes.addAll(generator.text('Kasir: $kasirName', + styles: const PosStyles(align: PosAlign.center))); + } + if (whatsapp != null && whatsapp.isNotEmpty) { + bytes.addAll(generator.text('WA: $whatsapp', + styles: const PosStyles(align: PosAlign.center))); + } + if (notes != null && notes.trim().isNotEmpty) { + final noteLines = notes.trim().split('\n'); + for (final line in noteLines) { + final text = line.trim(); + if (text.isEmpty) continue; + bytes.addAll(generator.text(text, + styles: const PosStyles(align: PosAlign.center))); + } + } + bytes.addAll(generator.hr()); + bytes.addAll(generator.text( + 'Terima kasih!', + styles: const PosStyles(align: PosAlign.center), + )); + bytes.addAll(generator.feed(2)); + bytes.addAll(generator.cut()); + return bytes; + } + + Future printSale(Sale sale, String storeName, {String? kasirName, String? whatsapp, String? notes}) async { + if (!_isConnected || _connectedMac == null) { + return 'Printer belum terhubung'; + } + try { + final bytes = await _buildReceiptBytes(sale, storeName, kasirName: kasirName, whatsapp: whatsapp, notes: notes); + final result = await PrintBluetoothThermal.writeBytes(bytes); + if (result) return null; + return 'Gagal mengirim ke printer'; + } catch (e) { + return e.toString(); + } + } +} + +final printerService = PrinterService(); diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart new file mode 100644 index 0000000..fe43c98 --- /dev/null +++ b/lib/state/app_state.dart @@ -0,0 +1,760 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../models/product.dart'; +import '../models/sale.dart'; +import '../models/user_profile.dart'; +import '../services/offline_queue_service.dart'; +import '../utils/format.dart'; +import '../config.dart'; + +class CartLine { + final Product product; + int qty; + bool isReseller; + + CartLine({ + required this.product, + this.qty = 1, + this.isReseller = false, + }); + + double get price => isReseller ? product.priceReseller : product.price; +} + +class AppState extends ChangeNotifier { + final SupabaseClient _supabase = Supabase.instance.client; + + // Client dengan service_role key untuk operasi admin (buat/edit/hapus akun kasir). + // PERINGATAN: key ini bypass RLS — hanya untuk app POS di device terpercaya. + final SupabaseClient _admin = SupabaseClient(supabaseUrl, supabaseServiceKey); + + static const Duration _timeout = Duration(seconds: 30); + + Future _withTimeout(Future future, [String? operation]) async { + try { + return await future.timeout( + _timeout, + onTimeout: () => throw TimeoutException('${operation ?? 'Operasi'} timeout setelah $_timeout'), + ); + } on TimeoutException catch (e) { + debugPrint('Supabase timeout: $e'); + rethrow; + } + } + + List products = []; + List sales = []; + List cart = []; + List> kasirAccounts = []; + bool loading = true; + String? error; + + static const int _pageSize = 30; + int _visibleProductCount = _pageSize; + int _visibleSalesCount = _pageSize; + + List get displayedProducts => + products.take(_visibleProductCount).toList(); + List get displayedSales => + sales.take(_visibleSalesCount).toList(); + + int get visibleProductCount => _visibleProductCount; + int get visibleSalesCount => _visibleSalesCount; + int get pageSize => _pageSize; + + bool get hasMoreProducts => _visibleProductCount < products.length; + bool get hasMoreSales => _visibleSalesCount < sales.length; + + void resetPagination() { + _visibleProductCount = _pageSize; + _visibleSalesCount = _pageSize; + notifyListeners(); + } + + void loadMoreProducts() { + if (!hasMoreProducts) return; + _visibleProductCount = (_visibleProductCount + _pageSize).clamp(0, products.length); + notifyListeners(); + } + + void loadMoreSales() { + if (!hasMoreSales) return; + _visibleSalesCount = (_visibleSalesCount + _pageSize).clamp(0, sales.length); + notifyListeners(); + } + + String customerType = 'umum'; + bool resellerEnabled = true; + String? userId; + String? userRole; + UserProfile? _profile; + final Map _profileNames = {}; + + double _discount = 0; + + bool get isAdmin => userRole == 'admin'; + bool get isKasir => userRole == 'kasir'; + bool get isLoggedIn => userId != null; + + String getProfileName(String? uid) { + if (uid == null) return 'Tidak diketahui'; + if (uid == userId) return _profile?.fullName ?? 'Admin'; + return _profileNames[uid] ?? 'Kasir'; + } + + AppState() { + _init(); + } + + Timer? _pollTimer; + static const Duration _pollInterval = Duration(minutes: 1); + DateTime? _lastManualRefresh; + + void recordManualRefresh() { + _lastManualRefresh = DateTime.now(); + } + + void startPolling() { + stopPolling(); + _pollTimer = Timer.periodic(_pollInterval, (_) => _poll()); + } + + void stopPolling() { + _pollTimer?.cancel(); + _pollTimer = null; + } + + Future _poll() async { + if (_lastManualRefresh != null) { + final elapsed = DateTime.now().difference(_lastManualRefresh!); + if (elapsed < const Duration(seconds: 15)) return; + } + await refresh(); + } + + Future refresh() async { + await _loadProducts(); + await _loadSales(); + notifyListeners(); + } + + final OfflineQueueService _offlineQueue = OfflineQueueService(); + + double get subtotal => + cart.fold(0, (sum, line) => sum + line.price * line.qty); + + double get discount => _discount; + + double get total => (subtotal - _discount).clamp(0, double.infinity); + + bool get canCheckout => cart.isNotEmpty && total > 0; + + /* ---------- Init & Realtime ---------- */ + Future _init() async { + try { + await _initAuth(); + await _loadProducts(); + await _loadSales(); + await loadKasirAccounts(); + await _loadProfileNames(); + await _loadSettings(); + _subscribe(); + await _seedAdminIfEmpty(); + await _offlineQueue.init(); + startPolling(); + } catch (e) { + error = e.toString(); + } + loading = false; + notifyListeners(); + } + + Future _loadSettings() async { + final prefs = await SharedPreferences.getInstance(); + resellerEnabled = prefs.getBool('reseller_enabled') ?? true; + notifyListeners(); + } + + Future setResellerEnabled(bool value) async { + resellerEnabled = value; + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool('reseller_enabled', value); + if (!value) { + setCustomerType('umum'); + for (final line in cart) { + if (line.isReseller) toggleLineMode(line.product.id); + } + } + notifyListeners(); + } + + Future _initAuth() async { + final session = _supabase.auth.currentSession; + if (session != null) { + userId = session.user.id; + await _loadProfile(); + } + } + + Future _loadProfile() async { + if (userId == null) return; + try { + final data = await _supabase + .from('profiles') + .select() + .eq('id', userId!) + .maybeSingle(); + if (data != null) { + _profile = UserProfile.fromJson(data); + userRole = _profile!.role; + } + } catch (_) {} + } + + Future _seedAdminIfEmpty() async { + try { + final count = await _withTimeout( + _admin.from('profiles').select().count(), + 'Check admin profiles', + ); + if (count.count == 0) { + await _withTimeout( + _admin.auth.admin.createUser( + AdminUserAttributes(email: 'admin@posgrosir.local', password: 'admin123'), + ), + 'Create default admin', + ); + } + } catch (_) {} + } + + Future login(String email, String password) async { + try { + final res = await _withTimeout( + _supabase.auth.signInWithPassword( + email: email, + password: password, + ), + 'Login', + ); + userId = res.user?.id; + await _loadProfile(); + notifyListeners(); + return null; + } on AuthException catch (e) { + return e.message; + } catch (e) { + return e.toString(); + } + } + + // Reserved for future self-service signup flow. + // Currently unused per PRD §5.3: all devices must be pre-provisioned by admin. + Future signup(String email, String password) async { + try { + final res = await _withTimeout( + _supabase.auth.signUp( + email: email, + password: password, + ), + 'Signup', + ); + userId = res.user?.id; + await _loadProfile(); + notifyListeners(); + return null; + } on AuthException catch (e) { + return e.message; + } catch (e) { + return e.toString(); + } + } + + Future logout() async { + await _withTimeout(_supabase.auth.signOut(), 'Logout'); + userId = null; + userRole = null; + _profile = null; + cart.clear(); + _discount = 0; + notifyListeners(); + } + + Future createKasir(String email, String password, String? name) async { + try { + final res = await _withTimeout( + _admin.auth.admin.createUser( + AdminUserAttributes(email: email, password: password, emailConfirm: true), + ), + 'Create kasir user', + ); + final newUserId = res.user?.id; + if (newUserId != null) { + await _withTimeout( + _admin.from('profiles').upsert({ + 'id': newUserId, + 'role': 'kasir', + 'full_name': name, + }), + 'Create kasir profile', + ); + await loadKasirAccounts(); + } + return null; + } on AuthException catch (e) { + return e.message; + } catch (e) { + return e.toString(); + } + } + + Future deleteKasir(String id) async { + try { + await _withTimeout( + _admin.from('profiles').delete().eq('id', id), + 'Delete kasir profile', + ); + await _withTimeout( + _admin.auth.admin.deleteUser(id), + 'Delete kasir user', + ); + await loadKasirAccounts(); + } catch (_) {} + } + + Future updateKasir(String id, String email, String? name, String? password) async { + try { + final updateData = { + 'full_name': name, + }; + + if (password != null && password.isNotEmpty) { + await _withTimeout( + _admin.auth.admin.updateUserById( + id, + attributes: AdminUserAttributes(password: password), + ), + 'Update kasir password', + ); + } + + await _withTimeout( + _admin.from('profiles').update(updateData).eq('id', id), + 'Update kasir profile', + ); + await loadKasirAccounts(); + return null; + } on AuthException catch (e) { + return e.message; + } catch (e) { + return e.toString(); + } + } + + Future loadKasirAccounts() async { + try { + final rows = await _withTimeout( + _admin + .from('profiles') + .select() + .eq('role', 'kasir'), + 'Load kasir accounts', + ); + + Map emails = {}; + try { + final usersRes = await _withTimeout( + _admin.auth.admin.listUsers(), + 'List auth users', + ); + for (final u in usersRes) { + if (u.email != null && u.email!.isNotEmpty) { + emails[u.id] = u.email!; + } + } + } catch (_) {} + + kasirAccounts = rows.map((r) { + final map = Map.from(r); + if ((map['email'] == null || map['email'].toString().isEmpty) && + emails.containsKey(map['id'])) { + map['email'] = emails[map['id']]; + } + if ((map['full_name'] == null || map['full_name'].toString().isEmpty) && + map['email'] != null && + map['email'].toString().isNotEmpty) { + map['full_name'] = map['email'].toString().split('@').first; + } + return map; + }).toList(); + notifyListeners(); + } catch (_) {} + } + + Future _loadProfileNames() async { + try { + final rows = await _withTimeout( + _admin.from('profiles').select('id,full_name,email'), + 'Load profile names', + ); + _profileNames.clear(); + for (final r in rows) { + final map = Map.from(r); + final name = (map['full_name']?.toString().trim().isEmpty == true + ? map['email']?.toString().split('@').first + : map['full_name']?.toString().trim()) ?? + ''; + if (name.isNotEmpty) { + _profileNames[map['id'] as String] = name; + } + } + } catch (_) {} + } + + void _subscribe() { + _supabase.auth.onAuthStateChange.listen((event) { + if (event.session != null) { + userId = event.session!.user.id; + _loadProfile(); + } else { + userId = null; + userRole = null; + _profile = null; + } + notifyListeners(); + }); + + _supabase.from('products').stream(primaryKey: ['id']).listen( + (rows) { + products = rows.map((e) => Product.fromJson(e)).toList(); + notifyListeners(); + }, + onError: (e) { + debugPrint('REALTIME products stream error: $e'); + }, + ); + + _supabase.from('sales').stream(primaryKey: ['id']).listen( + (rows) { + sales = rows.map((e) => Sale.fromJson(e)).toList(); + sales.sort((a, b) => b.date.compareTo(a.date)); + notifyListeners(); + }, + onError: (e) { + debugPrint('REALTIME sales stream error: $e'); + }, + ); + } + + Future _loadProducts() async { + final rows = await _withTimeout( + _supabase.from('products').select().order('name'), + 'Load products', + ); + products = rows.map((e) => Product.fromJson(e)).toList(); + if (products.isEmpty) _seed(); + } + + Future _loadSales() async { + final rows = await _withTimeout( + _supabase + .from('sales') + .select() + .order('created_at', ascending: false), + 'Load sales', + ); + sales = rows.map((e) => Sale.fromJson(e)).toList(); + sales.sort((a, b) => b.date.compareTo(a.date)); + } + + Future _seed() async { + final seeds = [ + Product(id: uid(), name: 'Beras 5kg', price: 58000, priceReseller: 55000, stock: 50), + Product(id: uid(), name: 'Minyak 2L', price: 32000, priceReseller: 30000, stock: 40), + Product(id: uid(), name: 'Gula 1kg', price: 14000, priceReseller: 13000, stock: 60), + Product(id: uid(), name: 'Teh Botol', price: 3600, priceReseller: 3200, stock: 120), + Product(id: uid(), name: 'Sabun Cuci', price: 8500, priceReseller: 7800, stock: 35), + Product(id: uid(), name: 'Indomie Dus', price: 95000, priceReseller: 90000, stock: 25), + ]; + await _withTimeout( + _supabase.from('products').insert(seeds.map((e) => e.toJson()).toList()), + 'Seed products', + ); + products = seeds; + notifyListeners(); + } + + /* ---------- Tipe Pembeli ---------- */ + void setCustomerType(String type) { + customerType = type; + final reseller = type == 'reseller'; + for (final c in cart) { + c.isReseller = reseller; + } + notifyListeners(); + } + + /* ---------- Produk ---------- */ + Future addProduct(String name, String barcode, double price, + double priceReseller, int stock, int minStock, double hargaPokok) async { + try { + final trimmed = barcode.trim(); + if (trimmed.isNotEmpty && + products.any((p) => p.barcode.trim().toLowerCase() == trimmed.toLowerCase())) { + return 'Barcode sudah digunakan oleh produk lain'; + } + final product = Product( + id: uid(), + name: name, + barcode: trimmed, + price: price, + priceReseller: priceReseller, + stock: stock, + minStock: minStock, + hargaPokok: hargaPokok, + ); + await _withTimeout( + _supabase.from('products').insert(product.toJson()), + 'Add product', + ); + } catch (e) { + return e.toString(); + } + try { + await _loadProducts(); + } catch (_) {} + notifyListeners(); + return null; + } + + Future updateProduct(String id, String name, String barcode, + double price, double priceReseller, int stock, int minStock, double hargaPokok) async { + try { + final trimmed = barcode.trim(); + if (trimmed.isNotEmpty && + products.any((p) => p.id != id && p.barcode.trim().toLowerCase() == trimmed.toLowerCase())) { + return 'Barcode sudah digunakan oleh produk lain'; + } + await _withTimeout( + _supabase.from('products').update({ + 'name': name, + 'barcode': trimmed, + 'price': price, + 'price_reseller': priceReseller, + 'stock': stock, + 'min_stock': minStock, + 'harga_pokok': hargaPokok, + }).eq('id', id), + 'Update product', + ); + } catch (e) { + return e.toString(); + } + try { + await _loadProducts(); + } catch (_) {} + notifyListeners(); + return null; + } + + Future deleteProduct(String id) async { + try { + cart.removeWhere((c) => c.product.id == id); + await _withTimeout( + _supabase.from('products').delete().eq('id', id), + 'Delete product', + ); + } catch (e) { + return e.toString(); + } + try { + await _loadProducts(); + } catch (_) {} + notifyListeners(); + return null; + } + + /* ---------- Cart ---------- */ + void addToCart(Product product) { + if (product.stock <= 0) return; + final line = cart.firstWhere( + (c) => c.product.id == product.id, + orElse: () => CartLine(product: product), + ); + if (cart.contains(line)) { + if (line.qty < product.stock) line.qty++; + } else { + line.isReseller = customerType == 'reseller'; + cart.add(line); + } + notifyListeners(); + } + + void changeQty(String productId, int delta) { + final line = cart.firstWhere((c) => c.product.id == productId); + line.qty += delta; + if (line.qty <= 0) { + cart.remove(line); + } else if (line.qty > line.product.stock) { + line.qty = line.product.stock; + } + notifyListeners(); + } + + void toggleLineMode(String productId) { + final line = cart.firstWhere((c) => c.product.id == productId); + line.isReseller = !line.isReseller; + notifyListeners(); + } + + void setDiscount(double value) { + _discount = value < 0 ? 0 : value.clamp(0, subtotal); + notifyListeners(); + } + + void clearCart() { + cart.clear(); + _discount = 0; + notifyListeners(); + } + + /* ---------- Checkout ---------- */ + Future checkout(double paid, {String paymentMethod = 'tunai', Map? splitPayment, String paymentStatus = 'paid', double dueAmount = 0.0, String? customerPhone}) async { + final totalCost = cart.fold(0.0, (sum, c) => sum + (c.product.hargaPokok * c.qty)); + final sale = Sale( + id: uid(), + date: DateTime.now(), + userId: userId, + items: cart + .map((c) => SaleItem( + productId: c.product.id, + name: c.product.name, + price: c.price, + qty: c.qty, + isReseller: c.isReseller, + )) + .toList(), + subtotal: subtotal, + discount: _discount, + total: total, + paid: paid, + change: paid - total, + totalCost: totalCost, + paymentMethod: paymentMethod, + paymentStatus: paymentStatus, + dueAmount: dueAmount, + customerPhone: customerPhone, + splitPayment: splitPayment, + ); + + try { + await _withTimeout( + _supabase.from('sales').insert(sale.toJson()), + 'Create sale', + ); + + for (final line in cart) { + try { + final current = + products.firstWhere((p) => p.id == line.product.id); + await _withTimeout( + _supabase + .from('products') + .update({'stock': current.stock - line.qty}) + .eq('id', line.product.id), + 'Update stock', + ); + } catch (_) {} + } + + await _loadProducts(); + await _loadSales(); + + cart.clear(); + _discount = 0; + notifyListeners(); + return sale; + } catch (e) { + await _offlineQueue.addToQueue({ + 'sale': sale.toJson(), + 'items': cart.map((c) { + final lineTotalCost = c.product.hargaPokok * c.qty; + return { + 'product_id': c.product.id, + 'qty': c.qty, + 'price': c.price, + 'total_cost': lineTotalCost, + }; + }).toList(), + }); + cart.clear(); + _discount = 0; + notifyListeners(); + rethrow; + } + } + + /* ---------- Retur / Pembatalan ---------- */ + Future cancelSale(String saleId) async { + try { + final sale = sales.firstWhere((s) => s.id == saleId); + + await _withTimeout( + _supabase.from('sales').update({'is_cancelled': true}).eq('id', saleId), + 'Cancel sale', + ); + + for (final item in sale.items) { + final product = products.firstWhere( + (p) => p.id == item.productId, + orElse: () => Product(id: '', name: '', price: 0, stock: 0, hargaPokok: 0), + ); + if (product.id.isNotEmpty) { + await _withTimeout( + _supabase + .from('products') + .update({'stock': product.stock + item.qty}) + .eq('id', product.id), + 'Restore stock', + ); + } + } + + await _loadProducts(); + await _loadSales(); + notifyListeners(); + return null; + } on PostgrestException catch (e) { + return e.message; + } catch (e) { + return e.toString(); + } + } + + Future recordPayment(String saleId, double amount) async { + try { + final sale = sales.firstWhere((s) => s.id == saleId); + final newPaid = sale.paid + amount; + final newDue = (sale.dueAmount - amount).clamp(0, double.infinity); + final newStatus = newDue <= 0 ? 'paid' : 'partial'; + await _withTimeout( + _supabase.from('sales').update({ + 'paid': newPaid, + 'due_amount': newDue, + 'payment_status': newStatus, + }).eq('id', saleId), + 'Record payment', + ); + await _loadSales(); + notifyListeners(); + return null; + } on PostgrestException catch (e) { + return e.message; + } catch (e) { + return e.toString(); + } + } +} diff --git a/lib/utils/colors.dart b/lib/utils/colors.dart new file mode 100644 index 0000000..90b2b49 --- /dev/null +++ b/lib/utils/colors.dart @@ -0,0 +1,26 @@ +import 'package:flutter/material.dart'; + +const kBackground = Color(0xFF0B1220); +const kSurface = Color(0xFF141C2E); +const kSurface2 = Color(0xFF1C2638); +const kBorder = Color(0xFF2A3650); +const kText = Color(0xFFE8EEF7); +const kMuted = Color(0xFF93A1B8); +const kAccent = Color(0xFFF59E0B); +const kSuccess = Color(0xFF22C55E); +const kDanger = Color(0xFFEF4444); + +const kRadius = 18.0; + +const List productPalette = [ + Color(0xFFF59E0B), + Color(0xFF22C55E), + Color(0xFF3B82F6), + Color(0xFFEC4899), +]; + +Color productAccent(String name) { + if (name.isEmpty) return productPalette.first; + final index = name.hashCode.abs() % productPalette.length; + return productPalette[index]; +} diff --git a/lib/utils/format.dart b/lib/utils/format.dart new file mode 100644 index 0000000..68ec5e7 --- /dev/null +++ b/lib/utils/format.dart @@ -0,0 +1,26 @@ +String formatRupiah(double number) { + final rounded = number.round(); + final formatted = rounded + .toString() + .replaceAllMapped(RegExp(r'\B(?=(\d{3})+(?!\d))'), (m) => '.'); + return 'Rp $formatted'; +} + +String formatTanggal(DateTime date) { + const bulan = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', + 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des' + ]; + return '${date.day} ${bulan[date.month - 1]} ${date.year}'; +} + +String formatWaktu(DateTime date) { + final j = date.hour.toString().padLeft(2, '0'); + final m = date.minute.toString().padLeft(2, '0'); + return '$j:$m'; +} + +String uid() { + return DateTime.now().microsecondsSinceEpoch.toRadixString(36) + + (DateTime.now().millisecond).toRadixString(36); +} diff --git a/lib/utils/rupiah_input.dart b/lib/utils/rupiah_input.dart new file mode 100644 index 0000000..d9451f7 --- /dev/null +++ b/lib/utils/rupiah_input.dart @@ -0,0 +1,60 @@ +import 'package:flutter/services.dart'; + +class RupiahInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate( + TextEditingValue oldValue, TextEditingValue newValue) { + if (newValue.text.isEmpty) { + return newValue; + } + + final digits = newValue.text.replaceAll(RegExp(r'[^0-9]'), ''); + if (digits.isEmpty) { + return const TextEditingValue(text: ''); + } + + final formatted = _formatRupiah(digits); + + int newOffset = formatted.length; + if (oldValue.text.isNotEmpty) { + final oldLength = oldValue.text.replaceAll(RegExp(r'[^0-9]'), '').length; + final newLength = digits.length; + final oldCursor = oldValue.selection.baseOffset; + + if (newLength < oldLength) { + final digitsBeforeCursor = oldValue.text.substring(0, oldCursor).replaceAll(RegExp(r'[^0-9]'), '').length; + newOffset = (digitsBeforeCursor).clamp(0, formatted.length); + } else if (oldCursor < oldValue.text.length) { + final digitsBeforeCursor = oldValue.text.substring(0, oldCursor).replaceAll(RegExp(r'[^0-9]'), '').length; + newOffset = (digitsBeforeCursor).clamp(0, formatted.length); + } + } + + return TextEditingValue( + text: formatted, + selection: TextSelection.collapsed(offset: newOffset), + ); + } + + String _formatRupiah(String digits) { + final buffer = StringBuffer(); + final len = digits.length; + for (int i = 0; i < len; i++) { + if (i > 0 && (len - i) % 3 == 0) { + buffer.write('.'); + } + buffer.write(digits[i]); + } + return buffer.toString(); + } + + static String formatNumber(int number) { + return RupiahInputFormatter()._formatRupiah(number.toString()); + } + + static int? getRawValue(String formattedText) { + final digits = formattedText.replaceAll(RegExp(r'[^0-9]'), ''); + if (digits.isEmpty) return null; + return int.tryParse(digits); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..d9d964a --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "app_grosir") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.grosir.app_grosir") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..3792af4 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) gtk_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "GtkPlugin"); + gtk_plugin_register_with_registrar(gtk_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..21d8f8b --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + gtk + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..90501be --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,144 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView *view) +{ + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "app_grosir"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "app_grosir"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/logo.png b/logo.png new file mode 100644 index 0000000..c1670f4 Binary files /dev/null and b/logo.png differ diff --git a/logo2.png b/logo2.png new file mode 100644 index 0000000..de080e2 Binary files /dev/null and b/logo2.png differ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..0da94d3 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,26 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import app_links +import connectivity_plus +import mobile_scanner +import path_provider_foundation +import print_bluetooth_thermal +import share_plus +import shared_preferences_foundation +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AppLinksMacosPlugin.register(with: registry.registrar(forPlugin: "AppLinksMacosPlugin")) + ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) + MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + PrintBluetoothThermalPlugin.register(with: registry.registrar(forPlugin: "PrintBluetoothThermalPlugin")) + SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..5543bba --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* app_grosir.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "app_grosir.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* app_grosir.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* app_grosir.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/app_grosir.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/app_grosir"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/app_grosir.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/app_grosir"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/app_grosir.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/app_grosir"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..dc1522d --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..7a9026f --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = app_grosir + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.grosir.appGrosir + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.grosir. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..839ae49 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,930 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + app_links: + dependency: transitive + description: + name: app_links + sha256: "5f88447519add627fe1cbcab4fd1da3d4fed15b9baf29f28b22535c95ecee3e8" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + app_links_linux: + dependency: transitive + description: + name: app_links_linux + sha256: f5f7173a78609f3dfd4c2ff2c95bd559ab43c80a87dc6a095921d96c05688c81 + url: "https://pub.dev" + source: hosted + version: "1.0.3" + app_links_platform_interface: + dependency: transitive + description: + name: app_links_platform_interface + sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + app_links_web: + dependency: transitive + description: + name: app_links_web + sha256: af060ed76183f9e2b87510a9480e56a5352b6c249778d07bd2c95fc35632a555 + url: "https://pub.dev" + source: hosted + version: "1.0.4" + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + barcode: + dependency: transitive + description: + name: barcode + sha256: "7b6729c37e3b7f34233e2318d866e8c48ddb46c1f7ad01ff7bb2a8de1da2b9f4" + url: "https://pub.dev" + source: hosted + version: "2.2.9" + bidi: + dependency: transitive + description: + name: bidi + sha256: "77f475165e94b261745cf1032c751e2032b8ed92ccb2bf5716036db79320637d" + url: "https://pub.dev" + source: hosted + version: "2.0.13" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + connectivity_plus: + dependency: "direct main" + description: + name: connectivity_plus + sha256: b5e72753cf63becce2c61fd04dfe0f1c430cc5278b53a1342dc5ad839eab29ec + url: "https://pub.dev" + source: hosted + version: "6.1.5" + connectivity_plus_platform_interface: + dependency: transitive + description: + name: connectivity_plus_platform_interface + sha256: "3c09627c536d22fd24691a905cdd8b14520de69da52c7a97499c8be5284a32ed" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + csv: + dependency: "direct main" + description: + name: csv + sha256: c6aa2679b2a18cb57652920f674488d89712efaf4d3fdf2e537215b35fc19d6c + url: "https://pub.dev" + source: hosted + version: "6.0.0" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + dart_jsonwebtoken: + dependency: transitive + description: + name: dart_jsonwebtoken + sha256: ad84e60181696513d04d5f2078e0bbc20365b911f46f647797317414bdc88fbe + url: "https://pub.dev" + source: hosted + version: "3.4.1" + dbus: + dependency: transitive + description: + name: dbus + sha256: "0ce9b0a839e6dee59a37a623d2fc26a35bbbe6404213e419b0d6411023d62645" + url: "https://pub.dev" + source: hosted + version: "0.7.14" + esc_pos_utils_plus: + dependency: "direct main" + description: + name: esc_pos_utils_plus + sha256: "2a22d281cb6f04600ba3ebd607ad8df03a4b2446d814007d22525bab4d50c2ff" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + functions_client: + dependency: transitive + description: + name: functions_client + sha256: e9685e9ab852a8b8e0579c867f6c9155da27317b294b3df796a536b8b8e0d253 + url: "https://pub.dev" + source: hosted + version: "2.6.4" + gotrue: + dependency: transitive + description: + name: gotrue + sha256: "360bba9606e58d5acc59a033ab64ae3cf571a6868f7a7267cb8e9a204b7bf1b2" + url: "https://pub.dev" + source: hosted + version: "2.26.0" + gtk: + dependency: transitive + description: + name: gtk + sha256: "4ff85b2a16724029dd9e5bbb5a94b6918f9973f74ba571c949d2002801879cf5" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + html: + dependency: transitive + description: + name: html + sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" + url: "https://pub.dev" + source: hosted + version: "0.15.6" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.dev" + source: hosted + version: "4.8.0" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + jwt_decode: + dependency: transitive + description: + name: jwt_decode + sha256: d2e9f68c052b2225130977429d30f187aa1981d789c76ad104a32243cfdebfbb + url: "https://pub.dev" + source: hosted + version: "0.3.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mime: + dependency: transitive + description: + name: mime + sha256: "801fd0b26f14a4a58ccb09d5892c3fbdeff209594300a542492cf13fba9d247a" + url: "https://pub.dev" + source: hosted + version: "1.0.6" + mobile_scanner: + dependency: "direct main" + description: + name: mobile_scanner + sha256: "0b466a0a8a211b366c2e87f3345715faef9b6011c7147556ad22f37de6ba3173" + url: "https://pub.dev" + source: hosted + version: "6.0.11" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + nm: + dependency: transitive + description: + name: nm + sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" + url: "https://pub.dev" + source: hosted + version: "0.5.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + passkeys_platform_interface: + dependency: transitive + description: + name: passkeys_platform_interface + sha256: "9610bd136b3382500390912ddd8517ee99505228b1af7b507b9c907f7e99a47d" + url: "https://pub.dev" + source: hosted + version: "2.8.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" + url: "https://pub.dev" + source: hosted + version: "2.5.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: e47a275b267873d5944ad5f5ff0dcc7ac2e36c02b3046a0ffac9b72fd362c44b + url: "https://pub.dev" + source: hosted + version: "3.12.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pointycastle: + dependency: transitive + description: + name: pointycastle + sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + postgrest: + dependency: transitive + description: + name: postgrest + sha256: "10e3f195e131eec944fa872644aed89b33b5be998f3fc77c87325db3927bc646" + url: "https://pub.dev" + source: hosted + version: "2.8.0" + print_bluetooth_thermal: + dependency: "direct main" + description: + name: print_bluetooth_thermal + sha256: "5d524b9c445779fa46796b84130e63530c81f04864fb2ecbce47a0f5c91d1788" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + provider: + dependency: "direct main" + description: + name: provider + sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272" + url: "https://pub.dev" + source: hosted + version: "6.1.5+1" + qr: + dependency: transitive + description: + name: qr + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + realtime_client: + dependency: transitive + description: + name: realtime_client + sha256: "0cfbe0047e2591eba348938e9b4e620d5b1a8df6c374757e8eb8645252b8387f" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + retry: + dependency: transitive + description: + name: retry + sha256: "822e118d5b3aafed083109c72d5f484c6dc66707885e07c0fbcb8b986bba7efc" + url: "https://pub.dev" + source: hosted + version: "3.1.2" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: fb5319f3aab4c5dda5ebb92dca978179ba21f8c783ee4380910ef4c1c6824f51 + url: "https://pub.dev" + source: hosted + version: "8.0.3" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: "251eb156a8b5fa9ce033747d73535bf53911071f8d3b6f4f0b578505ce0d4496" + url: "https://pub.dev" + source: hosted + version: "3.4.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + storage_client: + dependency: transitive + description: + name: storage_client + sha256: "221263cfbe0c01575b7d7fe7543e44abff380eb4d38d936372844a1caa85ba12" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + supabase: + dependency: transitive + description: + name: supabase + sha256: "3879996256325fcc9abb03b62b12c07e4eaae2e008e1bf043cc1525184159a43" + url: "https://pub.dev" + source: hosted + version: "2.14.0" + supabase_flutter: + dependency: "direct main" + description: + name: supabase_flutter + sha256: c9916c1cd512ebf3107ec0f83c9dca13d2e1e789629c2a5df896586bff46ce5f + url: "https://pub.dev" + source: hosted + version: "2.16.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + url: "https://pub.dev" + source: hosted + version: "0.7.6" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: transitive + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "3bb000251e55d4a209aa0e2e563309dc9bb2befea2295fd0cec1f51760aac572" + url: "https://pub.dev" + source: hosted + version: "6.3.29" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: cfde38aa257dae62ffe79c87fab20165dfdf6988c1d31b58ebf59b9106062aad + url: "https://pub.dev" + source: hosted + version: "6.3.6" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.dev" + source: hosted + version: "15.2.0" + web: + dependency: transitive + description: + name: web + sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" + url: "https://pub.dev" + source: hosted + version: "0.5.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + win_ble: + dependency: transitive + description: + name: win_ble + sha256: "2a867e13c4b355b101fc2c6e2ac85eeebf965db34eca46856f8b478e93b41e96" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yet_another_json_isolate: + dependency: transitive + description: + name: yet_another_json_isolate + sha256: eaa26beb5990b25a49d942374fd5a0c5aa67a837e03b14b4c26134aaa1ed01a9 + url: "https://pub.dev" + source: hosted + version: "2.1.1" +sdks: + dart: ">=3.9.2 <4.0.0" + flutter: ">=3.35.6" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..acd2fdd --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,100 @@ +name: app_grosir +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.1+2 + +environment: + sdk: ^3.9.2 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + provider: ^6.1.2 + supabase_flutter: ^2.8.0 + mobile_scanner: ^6.0.0 + shared_preferences: ^2.3.0 + connectivity_plus: ^6.0.0 + pdf: ^3.11.0 + csv: ^6.0.0 + path_provider: ^2.1.2 + share_plus: ^8.0.0 + print_bluetooth_thermal: 1.2.1 + esc_pos_utils_plus: ^2.0.4 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/ss/Screenshot_1784141157.png b/ss/Screenshot_1784141157.png new file mode 100644 index 0000000..2eb11c7 Binary files /dev/null and b/ss/Screenshot_1784141157.png differ diff --git a/supabase/migrations/20240101_add_cancel_and_min_stock.sql b/supabase/migrations/20240101_add_cancel_and_min_stock.sql new file mode 100644 index 0000000..04d9c5d --- /dev/null +++ b/supabase/migrations/20240101_add_cancel_and_min_stock.sql @@ -0,0 +1,15 @@ +-- Migration: Add is_cancelled to sales and min_stock to products +-- Run this in Supabase Dashboard > SQL Editor + +-- Add is_cancelled column to sales table +ALTER TABLE sales + ADD COLUMN IF NOT EXISTS is_cancelled BOOLEAN DEFAULT false; + +-- Add min_stock column to products table +ALTER TABLE products + ADD COLUMN IF NOT EXISTS min_stock INTEGER DEFAULT 5; + +-- Update existing products to have default min_stock if null +UPDATE products + SET min_stock = 5 + WHERE min_stock IS NULL; diff --git a/supabase/migrations/20240102_add_harga_pokok_and_profit.sql b/supabase/migrations/20240102_add_harga_pokok_and_profit.sql new file mode 100644 index 0000000..6ba358c --- /dev/null +++ b/supabase/migrations/20240102_add_harga_pokok_and_profit.sql @@ -0,0 +1,20 @@ +-- Migration: Add harga_pokok to products and total_cost to sales +-- Run this in Supabase Dashboard > SQL Editor + +-- Add harga_pokok column to products table +ALTER TABLE products + ADD COLUMN IF NOT EXISTS harga_pokok numeric DEFAULT 0; + +-- Add total_cost column to sales table +ALTER TABLE sales + ADD COLUMN IF NOT EXISTS total_cost numeric DEFAULT 0; + +-- Update existing products to have default harga_pokok if null +UPDATE products + SET harga_pokok = 0 + WHERE harga_pokok IS NULL; + +-- Update existing sales to have default total_cost if null +UPDATE sales + SET total_cost = 0 + WHERE total_cost IS NULL; diff --git a/supabase/migrations/20240103_add_payment_method.sql b/supabase/migrations/20240103_add_payment_method.sql new file mode 100644 index 0000000..13968ae --- /dev/null +++ b/supabase/migrations/20240103_add_payment_method.sql @@ -0,0 +1,9 @@ +-- Migration: add payment method fields to sales table +-- Run this in Supabase SQL Editor before using payment features + +ALTER TABLE sales + ADD COLUMN IF NOT EXISTS payment_method text NOT NULL DEFAULT 'tunai', + ADD COLUMN IF NOT EXISTS split_payment jsonb; + +-- Optional: add index for filtering by payment method +CREATE INDEX IF NOT EXISTS idx_sales_payment_method ON sales(payment_method); diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..b3f02cf --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:app_grosir/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/test_syntax.dart b/test_syntax.dart new file mode 100644 index 0000000..c4356cb --- /dev/null +++ b/test_syntax.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; + +void test(BuildContext context) { + final _scrollController = ScrollController(); + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) { + final bottomInset = MediaQuery.of(context).viewInsets.bottom; + return Container( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(context).size.height * 0.92 - bottomInset, + ), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only(top: 12), + width: 40, + height: 4, + decoration: BoxDecoration( + color: Colors.grey, + borderRadius: BorderRadius.circular(4), + ), + ), + Expanded( + child: SingleChildScrollView( + controller: _scrollController, + padding: EdgeInsets.fromLTRB(16, 8, 16, 16 + bottomInset), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField(decoration: InputDecoration(labelText: 'Test 1')), + TextField(decoration: InputDecoration(labelText: 'Test 2')), + TextField(decoration: InputDecoration(labelText: 'Test 3')), + ], + ), + ), + ), + ], + ), + ); + }, + ); +} diff --git a/test_syntax2.dart b/test_syntax2.dart new file mode 100644 index 0000000..1280b68 --- /dev/null +++ b/test_syntax2.dart @@ -0,0 +1,238 @@ +import 'package:flutter/material.dart'; + +void test(BuildContext context) { + final name = TextEditingController(); + final barcode = TextEditingController(); + final price = TextEditingController(); + final priceReseller = TextEditingController(); + final stock = TextEditingController(); + final minStockCtrl = TextEditingController(text: '5'); + final hargaPokokCtrl = TextEditingController(); + final focusNodes = [ + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + FocusNode(), + ]; + final _scrollTimers = {}; + for (final node in focusNodes) { + node.addListener(() { + if (!node.hasFocus) { + _scrollTimers[node]?.cancel(); + _scrollTimers.remove(node); + } else if (context.mounted) { + _scrollTimers[node]?.cancel(); + _scrollTimers[node] = Timer(const Duration(milliseconds: 350), () { + if (node.context != null && node.context!.mounted) { + Scrollable.ensureVisible( + node.context!, + duration: const Duration(milliseconds: 250), + alignment: 0.1, + ); + } + _scrollTimers.remove(node); + }); + } + }); + } + + final _scrollController = ScrollController(); + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) { + final bottomInset = MediaQuery.of(context).viewInsets.bottom; + return Container( + constraints: BoxConstraints( + maxHeight: MediaQuery.of(context).size.height * 0.92 - bottomInset, + ), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + border: Border(top: BorderSide(color: Colors.grey)), + ), + child: Column( + children: [ + Container( + margin: const EdgeInsets.only(top: 12), + width: 40, + height: 4, + decoration: BoxDecoration( + color: Colors.grey, + borderRadius: BorderRadius.circular(4), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + children: [ + const Icon(Icons.add_box_outlined, color: Colors.amber), + const SizedBox(width: 8), + const Text('Tambah Produk', + style: TextStyle( + fontSize: 16, fontWeight: FontWeight.w700)), + const Spacer(), + IconButton( + icon: const Icon(Icons.close, color: Colors.grey), + onPressed: () => Navigator.pop(sheetContext), + tooltip: 'Tutup', + ), + ], + ), + ), + const Divider(height: 12), + Expanded( + child: SingleChildScrollView( + controller: _scrollController, + padding: EdgeInsets.fromLTRB(16, 8, 16, 16 + bottomInset), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: barcode, + focusNode: focusNodes[0], + decoration: InputDecoration( + labelText: 'Barcode / No. Produk', + prefixIcon: const Icon(Icons.qr_code_2_outlined), + suffixIcon: IconButton( + icon: const Icon(Icons.qr_code_scanner_outlined, color: Colors.amber), + onPressed: () async { + final code = await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const Scaffold(body: Center(child: Text('Scan'))), + ), + ); + if (code != null && context.mounted) { + barcode.text = code; + } + }, + tooltip: 'Scan barcode', + )), + ), + const SizedBox(height: 10), + TextField( + controller: name, + focusNode: focusNodes[1], + decoration: const InputDecoration( + labelText: 'Nama produk', + prefixIcon: Icon(Icons.label_outline)), + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextField( + controller: price, + focusNode: focusNodes[2], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Harga Umum', + prefixText: 'Rp ', + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: TextField( + controller: priceReseller, + focusNode: focusNodes[3], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Harga Reseller', + prefixText: 'Rp ', + ), + ), + ), + ], + ), + const SizedBox(height: 10), + TextField( + controller: stock, + focusNode: focusNodes[4], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Stok awal', + prefixIcon: Icon(Icons.numbers), + ), + ), + const SizedBox(height: 10), + TextField( + controller: hargaPokokCtrl, + focusNode: focusNodes[5], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Harga Pokok (modal)', + prefixText: 'Rp ', + helperText: 'Kosongkan jika tidak diketahui', + ), + ), + const SizedBox(height: 10), + TextField( + controller: minStockCtrl, + focusNode: focusNodes[6], + keyboardType: TextInputType.number, + decoration: const InputDecoration( + labelText: 'Stok minimum (warning)', + prefixIcon: Icon(Icons.warning_outlined), + helperText: 'Default: 5', + ), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: () async { + final n = name.text.trim(); + final bc = barcode.text.trim(); + final pr = (price.text.isEmpty ? 0 : double.tryParse(price.text) ?? 0); + final prR = (priceReseller.text.isEmpty ? pr : double.tryParse(priceReseller.text) ?? pr); + final st = int.tryParse(stock.text) ?? 0; + final ms = int.tryParse(minStockCtrl.text) ?? 5; + final hp = (hargaPokokCtrl.text.isEmpty ? 0 : double.tryParse(hargaPokokCtrl.text) ?? 0); + if (n.isEmpty || pr <= 0) return; + final err = 'OK'; // await state.addProduct(n, bc, pr, prR, st, ms, hp); + if (!context.mounted) return; + final messenger = ScaffoldMessenger.of(context); + if (err == null) { + name.clear(); + barcode.clear(); + price.clear(); + priceReseller.clear(); + stock.clear(); + minStockCtrl.clear(); + hargaPokokCtrl.clear(); + messenger.showSnackBar( + const SnackBar( + content: Text('Produk berhasil ditambahkan'), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(sheetContext); + } else { + messenger.showSnackBar( + SnackBar( + content: Text('Gagal menambah produk: $err'), + backgroundColor: Colors.red, + ), + ); + } + }, + icon: const Icon(Icons.add), + label: const Text('Tambah Produk'), + ), + ), + ], + ), + ), + ], + ), + ); + }, + ); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..8d1db8c --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + app_grosir + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..1122a85 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "app_grosir", + "short_name": "app_grosir", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..026f630 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(app_grosir LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "app_grosir") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..4dbc5cb --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,26 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + AppLinksPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AppLinksPluginCApi")); + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); + PrintBluetoothThermalPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PrintBluetoothThermalPluginCApi")); + SharePlusWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..805a9c3 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,29 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + app_links + connectivity_plus + print_bluetooth_thermal + share_plus + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..0f57a91 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.grosir" "\0" + VALUE "FileDescription", "app_grosir" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "app_grosir" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.grosir. All rights reserved." "\0" + VALUE "OriginalFilename", "app_grosir.exe" "\0" + VALUE "ProductName", "app_grosir" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..1a589ca --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"app_grosir", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_